如何从派生类函数调用父类函数? [英] How to call a parent class function from derived class function?
问题描述
如何使用C ++从派生类调用父函数?例如,我有一个名为 parent
的类,以及从父类派生的 child
类。在
中,每个类都有一个 print
函数。在子打印函数的定义中,我想调用父打印函数。
How do I call the parent function from a derived class using C++? For example, I have a class called parent
, and a class called child
which is derived from parent. Within
each class there is a print
function. In the definition of the child's print function I would like to make a call to the parents print function. How would I go about doing this?
推荐答案
我会冒这个明显的风险:你调用函数if它定义在基类中,它在派生类中自动可用(除非它 private
)。
I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private
).
在派生类中具有相同签名的函数可以通过添加基类的名称后跟两个冒号 base_class :: foo(...)
来消除歧义。您应该注意,与Java和C#不同,C ++ 不为基类( super
或 base
),因为C ++支持多重继承,这可能会导致歧义。
If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons base_class::foo(...)
. You should note that unlike Java and C#, C++ does not have a keyword for "the base class" (super
or base
) since C++ supports multiple inheritance which may lead to ambiguity.
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();
}
};
顺便说一下,你不能直接从同一个类派生两次,因为没有办法
Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.
class bottom : public left, public left { // Illegal
};
这篇关于如何从派生类函数调用父类函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!