Nav*_*een 4 c++ inheritance class anonymous-class
在Java中,可以在初始化时为特定对象修改类结构:
Car ford = new Car(){
public float price;
};
Run Code Online (Sandbox Code Playgroud)
因此,福特对象获得了一个名为price的新属性,而其他车则没有.
有没有一种方法可以在C++中获得类似的功能,而无需创建整个子类?
谢谢!
在C++中没有你不能按照你提到的方式去做.您可以使用匿名类来满足您的要求.
class car {
public:
void test() { cout << "test" << endl; }
};
int main() {
struct : public car { int price; } fordcar;
fordcar.test();
return 0;
}
Run Code Online (Sandbox Code Playgroud)