c++构造函数的调用方法

#include<iostream>
using namespace std;

class Base
{
public:

    Base(){
        cout<<"hello"<<endl;
    }

    Base (int _a ):base(_a){  // 将_a赋值给base
        base++;
        cout << base << endl;
    }

    Base (int _a ,float _b):base(_a),th(_b){
        cout << base + th << endl;
    }

    Base (int _a ,float _b ,int _c):base(_a),th(_b),xh(_c){
        cout << base + th + xh<< endl;
    }
    void fun0(){cout << base << endl;}
    int base;
    float th;
    int xh;
};

int main(){
    // Base b;  只有一个构造函数时才能这样调用否则报错
    Base c();   // 调用默认构造函数
    Base t(10);  // 调用带参的构造函数的简写形式 
    t.fun0();
    t.base=100;
    t.fun0();
    Base t1 =Base(100,88.12); // 调用带参的构造函数
    Base t2 =(10,100.12,20);  // 
}

 注意:Base t2 =(10,100.12,20); 在乌班图下输出的结果为错误的。 

猜你喜欢

转载自www.cnblogs.com/ligei/p/11443336.html