gpt4 book ai didi

c++ - 虚拟成员类的调用方法

转载 作者:行者123 更新时间:2023-11-30 00:44:06 27 4
gpt4 key购买 nike

我知道 virtual 在成员函数的上下文中是如何工作的,但是我在网上看到一篇关于虚拟成员类的文章让我感到困惑。

我找到的例子是这样的:

class Machine
{
void run () {}

virtual class Parts
{
};
};

// The inner class "Parts" of the class "Machine" may return the number of wheels the machine has.
class Car: public Machine
{
void run() {
cout << "The car is running." << endl;
}
class Parts
{
int get_Wheels () {
cout << "A car has 4 wheels." << endl;
return 4;
}
string get_Fuel_Type () {
cout << "A car uses gasoline for fuel." << endl;
return "gasoline";
}
};
};

文章 https://en.wikipedia.org/wiki/Virtual_class声明:

Any object of class type Machine can be accessed the same way. The programmer can ask for the number of wheels (by calling get_Wheels()), without needing to know what kind of machine it is, how many wheels that machine has, or all the possible types of machines there are. Functions like get_Fuel_Type() can be added to the virtual class Parts by the derived class Car.

如何从 Machine* 调用 get_Wheels() 或成员类 Parts 中的任何其他函数?在调用 get_wheels() 之前,您似乎必须知道您拥有哪种类型的 Machine,因为您无法保证该函数具有实现。

最佳答案

您发布的代码不是 C++,因为这种语言不支持您描述的概念中的虚拟类

关于c++ - 虚拟成员类的调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50684046/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com