企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[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/>