说明
- 写类的构造函数时,如果不加
explicit
进行修饰时,可能会发生一些隐式转换 - 对于一个类,如果没有找到需要进行隐式转换的理由,则建议加上explicit进行修饰,避免不可预料的转换问题
代码
#include<iostream>
#include<exception>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>
#include<iterator>
#include<list>
#include<deque>
#include<stack>
#include<queue>
#include<concurrent_priority_queue.h>
#include<algorithm>
#include<numeric>
#include<functional> //bind
#include<map>
#include<set>
#include<unordered_map>
#include<memory>
#include<assert.h>
#include<tuple>
#include<regex>
using namespace std;
class ExplicitClass
{
public:
ExplicitClass(string s) : height(0), width(0)
{
name = s;
cout << name << " has been initalized!" << endl;
}
int compare(const ExplicitClass &ec)
{
return strcmp(name.c_str(), ec.name.c_str());
}
private:
double height;
double width;
string name;
};
int main()
{
cout << "start!" << endl;
ExplicitClass c1("aa");
string n("bb");
cout << c1.compare(n) << endl;
cout << "end!" << endl;
system("pause");
return EXIT_SUCCESS;
}
* 说明:上面的代码中,没有加上explicit
,则在传入字符串进行compare
时,发现也构造一个ExplicitClass
的临时对象(运行时可以发现有两次构造输出)
* 如果将构造函数改为
explicit ExplicitClass(string s) : height(0), width(0)
{
name = s;
cout << name << " has been initalized!" << endl;
}
则会发生编译错误,因为不允许隐式转换