简体   繁体   English

关于继承/方法重写C ++的问题

[英]Question about Inheritance / Method overriding C++

class Class1
{
public:
    void print()
    {
        cout << "test" << endl;
    }

    void printl()
    {
        print();
    }
};

class Class2 : public Class1
{
public:
    void print()
    {
        cout << "test2" << endl;
    }
};

Why does print() not get overridden in Class2, is there any way a function can be overridden like this? 为什么print()不会在Class2中被覆盖,是否有任何方法可以像这样覆盖一个函数? (Without virtual functions). (没有虚函数)。 Thanks 谢谢

    Class2 t;
    t.printl();

No. This is the entire reason for virtual functions. 不。这是虚拟功能的全部原因。

Without a virtual method here, when printl() calls print(), it's calling Class1.print() , which prints "test". 这里没有虚方法,当printl()调用print()时,它调用Class1.print() ,它打印“test”。 If you flag the method as virtual, then it will handle it as you were expecting. 如果您将方法标记为虚拟,那么它将按您的预期处理它。

No, there is no way to override non-virtual functions. 不,没有办法覆盖非虚函数。 That's what virtual functions are for. 这就是虚拟功能的用途。

What you want is called a virtual method . 你想要的是一种虚拟方法 Simply write virtual void print() where you currently have void print() , and it will work as you expect. 只需编写virtual void print() ,您当前有void print() ,它将按预期工作。 Be aware that this will not work in constructors or destructors. 请注意,这在构造函数或析构函数中不起作用。

The call to print inside of printl is not overriden because it's not a virtual method. printl内部打印调用未被覆盖,因为它不是虚方法。 It`sa non-virtual method and hence is being invoked non-virtually. 它是一种非虚方法,因此是非虚拟调用的。 If you want to be overridable by a child class then make it virtual. 如果您希望被子类覆盖,则将其设为虚拟。

Imagine you had Class2, Class3 and Class3, all "overriding" Class1's "print" method. 想象一下,你有Class2,Class3和Class3,都是“覆盖”Class1的“打印”方法。

When Class1::printl is called - how is it meant to know which of the 3 overrides to call? 当调用Class1 :: printl时 - 如何知道调用哪3个覆盖? Without virtual methods the printl implementation has no way of knowing which overriding method to choose. 如果没有虚方法,printl实现无法知道选择哪种重写方法。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM