有没有办法可以在派生类上调用基类的成员函数?
Class Bass{
public:
void func();
};
Class Derived: public Base{
public:
void func();
};
我有一个期中练习,我怀疑没有,因为基类如何知道派生类,但我不确定。
最佳答案
Is there a way you can invoke a member function of a base class upon a class derived from it?
不确定您的意思,但鉴于您的 Base
和 Derived
类,您可以执行以下操作。只需确保您使用引用或指针,而不是按值传递,因为 slicing problem .
从 Derived::func()
中调用 Base::func()
:
void Derived::func()
{
Base::func();
}
在 Derived
对象上显式调用 Base::func()
:
Derived d;
d.Base::func();
I [...] am wondering if you could do something like
Base::func(Derived d)
正如其他人所指出的,您可以使用前向声明来做到这一点:
// Tell the compiler "Derived" is a class name.
class Derived;
class Base
{
// Can use the class name since it has been declared.
void func(Derived& derived);
};
// Define the class named "Derived".
class Derived : public Base
{
// ...
};
// Use the derived class.
void Base::func(Derived& derived)
{
// For this bit to work, the definition of `Derived` must
// be visible at this point (like putting the class above
// or including your "Derived.h" from "Base.cpp").
derived.some_derived_method();
}
但是,您将无法直接在类定义中定义 Base::func(Derived&)
,因为您需要完成定义 Base
并定义首先派生
。
关于C++ 派生函数与基函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9573195/