C++中的合成语法
Composition syntax in C++
我正在C++中使用作曲和类。我遇到的代码片段通过以下方式实现组合:
#include<iostream>
using namespace std;
class Engine {
public:
int power;
};
class Car {
public:
Engine e;
string company;
string color;
void show_details() {
cout << "Compnay is: " << company << endl;
cout << "Color is: " << color << endl;
cout << "Engine horse power is: " << e.power << endl;
}
};
int main() {
Car c;
c.e.power = 500;
c.company = "hyundai";
c.color = "black";
c.show_details();
return 0;
}
这编译良好,并运行。 我不喜欢这个实现的一件事是函数"void show_details"的实际位置,我更愿意把它放在外面。
但是,如果我天真地尝试执行以下操作:
#include<iostream>
using namespace std;
class Engine {
public:
int power;
};
class Car {
public:
//Engine e;
string company;
string color;
void show_details();
//void show_details() {
// cout << "Compnay is: " << company << endl;
// cout << "Color is: " << color << endl;
// cout << "Engine horse power is: " << e.power << endl;
//}
};
void Car::show_details(){
cout << "Compnay is: " << company << endl;
cout << "Color is: " << color << endl;
cout << "Engine horse power is: " << e.power << endl;
}
int main() {
Car c;
c.e.power = 500;
c.company = "hyundai";
c.color = "black";
c.show_details();
return 0;
}
G++ 返回以下错误:
comp3.cpp: In member function ‘void Car::show_details()’:
comp3.cpp:22:44: error: ‘e’ was not declared in this scope
cout << "Engine horse power is: " << e.power << endl;
^
comp3.cpp: In function ‘int main()’:
comp3.cpp:26:9: error: ‘class Car’ has no member named ‘e’
c.e.power = 500;
我显然对范围界定问题感到困惑,但我不确定缺失的部分是什么。
感谢您的任何帮助!!
在第二个示例中,您注释掉了e
.
//Engine e;
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 助记符和指向成员语法的指针
- 有人能分解一下这个c++模板的语法吗
- C++避免重复声明的语法是什么
- QMetaObject invokeMethod的基于函数指针的语法
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 单独定义模板化嵌套类方法的正确语法
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 错误 C2760:语法错误:映射迭代器上意外的标记"标识符",预期的";"
- 为什么我会收到错误 C2143 语法错误:缺少"*"之前的';'?
- 奇怪的代码抛出编译错误模板< J,int aSize=10> C2143:语法错误:在"<"之前缺少";"
- 使用基类指针调用基类的值构造函数的语法是什么?
- 很好的语法来获取对向量/数组数据的大小引用?
- C++语法运算符功能?
- C++使用 rand 定义函数语法
- 什么文件可以修改 atom 的C++语法?
- 创建模板嵌套类实例的语法?
- C++语法差异:二维和一维数组(指针算术)
- 将信息输入到下面显示的结构向量中的正确语法/格式是什么