隐式和显式构造

显示构造

所有创建对象,并传入初始化参数的写法。

例如,

    1 	 NODE n(24);
    2 	 NODE n(34,43);    
    3 	 new NODE(24,43);

隐式构造

C++有隐式构造的机制。

传递的参数不符合函数类型时,他会看其他重载函数需要的对象类型中,有没有单参数的构造函数能匹配传递的参数。如果匹配,就隐式构造一个该类型,然后调用这个函数。

    1 	#include<string>
    2 	#include<iostream>
    3 	using std::cout;
    4 	using std::endl;
    5 	using std::string;
    6 	struct NODE {
    7 		NODE() {
    8 	
    9 		}
   10 		explicit NODE(int) {//被explicit修饰的关键字,无法被隐式构造机制调用
   11 			cout << "int构造" << endl;
   12 		}
   13 		NODE(double) {
   14 			cout << "double构造" << endl;
   15 		}
   16 		NODE(int, int) {
   17 			cout << "int,int构造" << endl;
   18 		}
   19 	};
   20 	void run(string str) {//隐式构造的string对象,C++默认情况下支持隐式构造(系统已经写好)
   21 		cout << "string构造" << endl;
   22 	}
   23 	void run(const char* s) {
   24 		cout << "const char*构造" << endl;
   25 	}
   26 	void func(NODE n) {
   27 	
   28 	}
   29 	int main() {
   30 		const char* p = "nihao";
   31 		run(p);
   32 		int d = 35;
   33 		func(d);
   34 		return 0;
   35 	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追梦偏执狂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值