继承中的函数定义

Function definition in Inheritance

本文关键字:定义 函数 继承      更新时间:2023-10-16

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

例:

#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的所有公共成员函数都被类two继承,为什么我不能使用类two的名称定义类one的函数?

为什么?

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

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

然后,您将拥有以下公共成员:

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 !!

这是一个在线演示

想要多态性?

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

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()时,将调用正确的函数(在线示例),除非您使用完全限定标识符专门插入精确指定的版本。