[英]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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.