🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 只有一个成员变量的类 有一些不太注意的缺省转换发生,如从字符串常量到'char*'的转换 <details> <summary>main.cpp</summary> ``` #include <iostream> #include <cstdlib> using namespace std; class classA { int x; public: classA(int x) { this->x = x; } classA(char *x) { this->x = atoi(x); } int getX() { return x; } }; int main ( ) { classA ca(5); //正常调用构造函数 cout << "x = " << ca.getX() << endl; ca = 100; //缺省调用classA(100) cout << "x = " << ca.getX() << endl; ca = "255"; //缺省调用classA("255") cout << "x = " << ca.getX() << endl; // 会发出警告: // main.cpp:17:8: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings] // ca = "255"; // ^ // x = 5 // x = 100 // x = 255 return 0; } ``` </details> <br/> ## 用explicit禁止默认转换 出现编译报错 <details> <summary>main.cpp</summary> ``` #include <iostream> #include <cstdlib> using namespace std; class classA { int x; public: explicit classA(int x) { this->x = x; } explicit classA(char *x) { this->x = atoi(x); } int getX() { return x; } }; int main ( ) { classA ca(5); //正常调用构造函数 cout << "x = " << ca.getX() << endl; ca = 100; //编译出错 cout << "x = " << ca.getX() << endl; ca = "255"; //编译出错 cout << "x = " << ca.getX() << endl; return 0; } ``` </details> <br/> ## 类的合成 当一个类的成员是另一个类时,称之为“合成(composite)” <details> <summary>main.cpp</summary> ``` #include <iostream> using namespace std; class classB { int x; public: classB(int x) { this->x = x; } int getB() { return x; } }; class classA { classB xb; public: //classA(classB b) { xb = b; } //编译出错 classA(classB b) : xb(b) {} //只能用这种方法 int getX() { return xb.getB(); } }; int main() { classB cb(5); //先定义一个classB的实例 classA ca(cb); //然后用这个实例创建classA的实例 cout << "x = " << ca.getX() << endl; return 0; } ``` </details> <br/>