17.explicit关键字

  c++提供了关键字explicit,禁止通过构造函数进行的隐式转换。声明为explicit的构造函数不能在隐式转换中使用。

[explicit注意]

● explicit用于修饰构造函数,防止隐式转化。

● 是针对单参数的构造函数(或者除了第一个参数外其余参数都有默认值的多参构造)而言。

class MyString{
public:
	explicit MyString(int n){
		cout << "MyString(int n)!" << endl;
	}
	MyString(const char* str){
		cout << "MyString(const char* str)" << endl;
	}
};

int main(){

	//给字符串赋值?还是初始化?
	//MyString str1 = 1; 
	MyString str2(10);

	//寓意非常明确,给字符串赋值
	MyString str3 = "abcd";
	MyString str4("abcd");

	return EXIT_SUCCESS;
}

错误:

//2022年9月20日20:23:11
#include <iostream>
using namespace std;

class Maker
{
public:
    //explicit只能放在构造函数前面,构造函数只有一个参数或其他参数有默认值时
    explicit Maker(int n)//防止编译器优化Maker m = 10;这种格式
    {

    }
};
int main()
{
    Maker m = 10;
    system("pause");
    return EXIT_SUCCESS;
}
posted @ 2022-09-20 20:32  CodeMagicianT  阅读(28)  评论(0)    收藏  举报