c++类的构造函数

 

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值