简体   繁体   English

在C ++中按类层次结构覆盖

[英]Overriding in C++ in a hierarchy of classes

In c++ in this hierarchy of classes 在C ++中这种类层次结构

class n1
{
public:
    virtual void tt() { cout << "n1" << endl; }
};
class n2:public n1
{
public:
     void tt() { cout << "n2" << endl; }
};
class n3:public n2
{
    void tt() { cout << "n3" << endl; }
};
int main()
{
    n1 *k = new n3;
    k->tt();
}

In the third class is tt overriding n1 virtual function or it is simply hiding the n2 implementation? 在第三类中,tt是重写n1虚函数还是只是隐藏n2实现?

In C# i get that you can override at any level in the hierarchy the virtual method from the lowest class..but i dont know if it is the same in C++. 在C#中,您可以在层次结构的任何级别上覆盖最低类的虚拟方法..但是我不知道在C ++中是否相同。

Class a
{
    virtual void func();
};
class b : a
{
    override func()
};
class c : b
{
    override func()
};

You are overriding it. 您正在覆盖它。

If you aren't sure whether your override is correct, we have a keyword called override (c++11 required), which makes sure your override fits the virtual function / method declaration. 如果您不确定覆盖是否正确,我们有一个名为override (需要c ++ 11)的关键字,它确保您的覆盖适合虚拟函数/方法声明。

This should clear things up: 这应该清除一切:

#include <iostream>
using namespace std;

class n1
{
public:
    virtual void tt() { cout << "n1" << endl; }
};

class n2:public n1
{
public:
    void tt() override { cout << "n2" << endl; }
};

class n3:public n2
{
    void tt() override { cout << "n3" << endl; }
};

int main()
{
    n1 *a = new n1;
    n1 *b = new n2;
    n1 *c = new n3;

    a->tt();
    b->tt();
    c->tt();

    delete a;
    delete b;
    delete c;
}

Outputs: 输出:
n1 N1
n2 N2
n3 N3

Live 生活

So in a 3 class hierarchy A->B->C if A has virtual method and B implements it ,it doesnt mean that classes derived from B will take the method already 因此,在3类层次结构A-> B-> C中,如果A具有虚拟方法并且B实现了该方法,这并不意味着从B派生的类将已经采用该方法

If you do override it, then that override will be used. 如果您确实要覆盖它,那么将使用该覆盖。

If you don't override the method, then the last overriden method will be used. 如果不重写该方法,则将使用最后一个重写的方法。

class n1
{
public:
    virtual void tt() { cout << "n1" << endl; }
};

class n2:public n1
{
public:
    void tt() override { cout << "n2" << endl; }
};

class n3:public n2
{

};

Outputs: 输出:
n1 N1
n2 N2
n2 N2

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

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