44 lines
791 B
C++
44 lines
791 B
C++
// explicit 关键字(禁止隐式转换)
|
|
#include <iostream>
|
|
|
|
using namespace std;
|
|
|
|
class Person
|
|
{
|
|
private:
|
|
int age;
|
|
string name;
|
|
|
|
public:
|
|
Person(const char *name, int age = 18)
|
|
{
|
|
this->name = name;
|
|
this->age = age;
|
|
}
|
|
// explicit 使得不存在从 "int" 转换到 "Person" 的适当构造函数
|
|
explicit Person(int age) // 进制 Person p = 值
|
|
{
|
|
this->age = age;
|
|
this->name = "disen";
|
|
}
|
|
|
|
public:
|
|
void show()
|
|
{
|
|
cout << name << ", " << age << endl;
|
|
}
|
|
};
|
|
|
|
int main()
|
|
{
|
|
Person p1 = "jack";
|
|
Person p2 = Person("doken", 9);
|
|
Person p3 = Person(1);
|
|
// Person p4 = 2; // 不存在从 "int" 转换到 "Person" 的适当构造函数
|
|
p1.show();
|
|
p2.show();
|
|
p3.show();
|
|
|
|
return 0;
|
|
}
|