【发布时间】:2018-09-01 06:54:11
【问题描述】:
在公开继承一个类时,如果基类的公共成员被派生类继承,为什么不能使用派生类的名称定义基类的函数?
例子:
#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类的函数呢?
【问题讨论】:
-
因为
class one不是抽象类——如果你实例化one的新实例,它应该使用什么实现? -
因为
a是private类one的成员,因此无法在类one之外访问。或者您的问题不清楚...您遇到了什么错误? -
你试过
override了吗?
标签: c++ function inheritance definition