c++ - 继承中的函数定义

标签 c++ function inheritance definition

当公共(public)继承一个类时,如果基类的公共(public)成员被派生类继承,为什么我不能使用派生类的名称定义基类的函数?

示例:

#include <iostream>
using namespace std;

class one{
    int a;
public:
    void get(int);
    void show();
};

class two:public one
{
    int b;
public:
    void getb(int);
    void dis();
};

void one::get(int x)  //if i write void two::get(int x) here it gives error
{
    a = x;
}
void one::show()  //same goes for this function why can't i define it as `void two::show()`?
{
  cout << a << endl;
}

int main()
{
    two ob;
    int x;
    cin >> x;
    ob.get( x );
    ob.show();
}

所以如果类 one 的所有公共(public)成员函数都被类 two 继承,为什么我不能定义类 one 的函数使用类名 two ?

最佳答案

为什么?

在类定义中,您说two 继承自one。因此它将具有以下公共(public)成员:

void get(int);       publicly inherited from one
void show();         publicly inherited from one
void getb(int);      own member
void dis();          own member

只能定义two自己的成员函数,这里是two::getb(int)two::dis() .但是你不能定义 two::show() 因为它是在一个中定义的,而你没有告诉编译器你想要它。

有没有办法拥有不同版本的继承函数?

如果您按如下方式定义类:

class two:public one
{
    int b;
public:
    void getb(int);
    void dis();
    void show();     //yes you can, but you'll have to define it 
};

那么您将拥有以下公共(public)成员:

void get(int);       publicly inherited from one
void one::show();    publicly inherited from one but hidden 
void show();         own member
void getb(int);      own member
void dis();          own member

您可以定义以下内容:

void two::show()  //no problem !!
{
  cout << "two's version" << endl;
}

你甚至可以在 main() 中选择你想调用哪一个:

ob.get( x );          // one::get(), because there's no two::get()
ob.show();            // by default two::show(), because ob is a two
ob.one::show();       // yes you can !!

这里是online demo

想要多态性?

在上面的所有代码中,调用的函数取决于用于访问对象的类型:

one *pob = &ob;  // a one pointer can point to a two object 
pob->show();     // but this will invoke one::show()

如果您希望根据对象的实际类型调用正确的函数,而不是根据类型声明假定的类型,您需要使用虚函数并覆盖它们:

class one{
    ... (the rest as before) ...
    virtual void show();
};

class two:public one
{
    ... (the rest as before) ...
    void show() override;  
};

然后,无论何时调用 show(),都会调用正确的函数 (online example),除非您使用完全限定的标识符特别指定了一个精确指定的版本。

关于c++ - 继承中的函数定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49435381/

相关文章:

c++ - 基类返回指向派生类的指针,而无需在 C++ 中显式强制转换

c++ - 如何使用 SFML 修复此段错误?

Ruby:如何将函数映射到散列

具有返回不同类型的子项的抽象类中的 C# 抽象方法

javascript - 根据更改选择获取替代数据值

javascript - 这是什么类型的结构?

没有继承的 Ruby 类重写

c++ - Steady_Clock 在主游戏循环的更新之间跳过

c++ - XCode std::thread C++

C++类名冲突