继承中的函数定义
Function definition in Inheritance
当公开继承一个类时,如果基类的公共成员被派生类继承,为什么我不能使用派生类的名称定义基类的函数?
例:
#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()
时,将调用正确的函数(在线示例),除非您使用完全限定标识符专门插入精确指定的版本。
相关文章:
- 在命名空间中定义函数还是限定函数
- 为什么在定义函数之前先声明它
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- 这个c++代码是如何在没有定义函数的情况下运行的
- 具有外部"c"和程序集的未定义函数
- 已定义函数时出现 G++ "未定义的引用"错误
- 将自定义函数传递到基抽象类中以延迟执行
- C++使用 rand 定义函数语法
- Arduino:在 loop() 和自定义函数中运行相同的代码时出现问题
- 将具有固定签名的自定义函数名称注入 CRTP
- 使用定义函数模板别名
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 在内联程序集中定义函数和从 C++ 调用时出现问题
- 在 Metal 着色器代码中,如何定义函数的 in/out 参数变量?
- 声明和定义函数静态会产生"undefined reference to function_name()"
- 朋友定义函数的名称空间是什么
- 介子 对用户定义函数的未定义引用
- 如何使用 "using" 关键字定义函数原型/签名
- 在 C 结构中定义C++函数