c++类的构造函数

it2025-04-30  9

 

class Class_dele

{

public:

//委托构造函数体有代码的话会先运行函数中代码,然后才会返回到委托者

Class_dele(string str, int num, char ch):

classstr(str), classnum(num), classch(ch)

{

cout <<"not "<< classstr << " " << classnum << " " << classch << endl;

}

//构造函数的默认值

Class_dele() :Class_dele("str1",1,'a') {}

Class_dele(string sstr) :Class_dele(sstr, 2, 'b')

{

cout <<"weituo "<< classstr << " " << classnum << " " << classch << endl;

}

Class_dele(int num) : Class_dele()

{

cout << num <<" "<< classstr << " " << classnum << " " << classch << endl;

}

 

//explicit:不允许类型转换,该关键字只能在类内部声明构造函数时使用,类外部定义不能重复使用

//explicit只有一个参数时有效

explicit Class_dele(float num)

{

cout << "explicit " << num << endl;

}

 

 

private:

string classstr;

int classnum;

char classch;

};

 

class conDebug

{

public:

constexpr conDebug(bool b = true) :hw(b), io(b), other(b) {}

//constexpr构造函数必须初始化所有数据成员,初始值使用constexpr构造或使用常量表达式

constexpr conDebug(bool h, bool i, bool o) : hw(h), io(i), other(o) {}

 

void set_hw(bool h)

{

hw = h;

}

void set_io(bool i)

{

io = i;

}

void set_other(bool o)

{

other = 0;

}

 

constexpr bool any()

{

return hw || io || other;

}

 

private:

bool hw;

bool io;

bool other;

};

 

 

 

int main()

{

Class_dele *classdele = new Class_dele();

Class_dele *classdele1 = new Class_dele("aaa");

Class_dele *classdele2 = new Class_dele(77);

 

//Class_dele(float num)构造函数为explicit不能转换参数类型

Class_dele *classdele3 = new Class_dele(3.14159f);

 

//constexpr参数必须是常量或constexpr表达式

constexpr conDebug io_sub(false, true, false);

if (io_sub.any())

{

cerr << "print appadsd" << endl;

}

 

//

const bool bo = false;

constexpr conDebug prod(bo);

if (prod.any())

{

cerr << "print prod" << endl;

}

 

return 0;

}

 

最新回复(0)