【发布时间】:2018-06-04 15:29:09
【问题描述】:
我知道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 的文章声称:
类类型机器的任何对象都可以以相同的方式访问。程序员可以询问轮子的数量(通过调用 get_Wheels()),而不需要知道它是什么类型的机器,机器有多少个轮子,或者所有可能的机器类型。 get_Fuel_Type()等函数可以通过派生类Car添加到虚拟类Parts中。
如何从Machine* 调用get_Wheels() 或成员类Parts 中的任何其他函数?似乎您必须知道您拥有什么样的Machine,才能调用get_wheels(),因为您无法保证该函数具有实现。
【问题讨论】:
-
维基百科文章中没有任何内容表明示例代码是 C++。
-
这不是合法的 C++ 代码ideone.com/zbih4s
-
@StephenM.Webb 好点,我假设它来自
cout的使用 -
@samuelnj 你是正确的混淆。感谢您指出这一点,+1。 wiki 文章需要编辑,但我做不到,所以如果有人可以,请做..
-
真的很奇怪他们怎么能把那篇文章搞得这么乱。我的意思是代码几乎是C++,你只需要删除
virtual,但这就是文章的内容......
标签: c++ oop inheritance