调用虚成员类的方法 [英] Calling methods of a virtual member class

查看:51
本文介绍了调用虚成员类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我发现的例子是这样的:

class 机器{无效运行(){}虚拟类零件{};};//Machine"类的内部类Parts"可能会返回机器的轮子数量.类车:公机{无效运行(){cout<<车子开着了."<<结束;}类零件{int get_Wheels () {cout<<一辆汽车有四个轮子."<<结束;返回 4;}字符串 get_Fuel_Type () {cout<<汽车使用汽油作为燃料."<<结束;返回汽油";}};};

https://en.wikipedia.org/wiki/Virtual_class 上的文章声称:

<块引用>

任何类型为 Machine 的对象都可以用同样的方式访问.程序员可以询问轮子的数量(通过调用 get_Wheels()),而不需要知道它是什么类型的机器,机器有多少个轮子,或者所有可能的机器类型.派生类 Car 可以将 get_Fuel_Type() 等函数添加到虚拟类 Parts 中.

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

解决方案

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

I know how virtual works in the context of member functions, but I saw an article online about virtual member classes that confuses me.

The example I found is this:

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";
        }
    };
};

The article at https://en.wikipedia.org/wiki/Virtual_class claims:

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.

How can one call get_Wheels() or any other function in the member class Parts from a Machine*? It seems like you would have to know what kind of Machine you have before being able to call get_wheels() since you have no guarantee that the function has an implementation.

解决方案

The code you posted is not C++, since this language doesn't support virtual classes in the notion that you describe.

这篇关于调用虚成员类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆