如何使用 C++ 从派生类调用父函数?例如,我有一个名为 的类parent
,以及一个child
从父级派生的名为 的类。每个类中都有一个print
函数。在孩子的打印功能的定义中,我想调用父母的打印功能。我该怎么做呢?
我将冒着说明显而易见的风险:你调用该函数,如果它是在基类中定义的,则它在派生类中自动可用(除非它是private
)。
如果派生类中存在具有相同签名的函数,你可以通过添加基类名称后跟两个冒号来消除歧义base_class::foo(...)
。你应该注意到,不像Java和C#,C ++并没有对“基础类”(关键字super
或base
),因为C ++支持多重继承,这可能导致歧义。
class left {
public:
void foo();
};
class right {
public:
void foo();
};
class bottom : public left, public right {
public:
void foo()
{
//base::foo();// ambiguous
left::foo();
right::foo();
// and when foo() is not called for 'this':
bottom b;
b.left::foo(); // calls b.foo() from 'left'
b.right::foo(); // call b.foo() from 'right'
}
};
顺便说一下,你不能直接从同一个类派生两次,因为没有办法引用一个基类而不是另一个基类。
class bottom : public left, public left { // Illegal
};
为什么要从同一个类继承两次?
@bluesm:在经典的 OOP 中它没有多大意义,但在泛型编程
template<class A, class B> class C: public A, public B {};
中,由于代码的使用方式(这使得 A 和 B 相同),可能会出现两种或三种相同的类型抽象层的方式来自不知道你做了什么的人。我认为补充一点很有用,即使它没有直接在父类中实现,而是在继承链中的父类之一中实现,它也会调用父类方法。
@Mathai 这就是为什么你不应该使用
using namespace std
.+1 用于说明
You should note that unlike Java and C#, C++ does not have a keyword for "the base class"
。