C++ 派生函数与基函数

标签 c++ function derived-class base-class

有没有办法可以在派生类上调用基类的成员函数?

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?

不确定您的意思,但鉴于您的 BaseDerived 类,您可以执行以下操作。只需确保您使用引用或指针,而不是按值传递,因为 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/

相关文章:

c++ - 为什么编译器提示不能用 Base 类型的右值初始化 "Derived"

c++ - 如何将一个 "unknown"的派生类声明为基类的成员,并允许派生版本的成员函数被调用?

C++ 多线程将模板化的 std::bind 提供给另一个线程

c++ - 可以使用位置信息编写改进的 cmake 日志记录宏吗?

python - python中的shell脚本中的 "&"相当于什么

php - 先返回 False 或 True 有什么区别?

javascript - ES6 构造函数返回基类的实例?

c++ - 哪种字符串查找算法适用于此?

java - NewDirectByteBuffer 是否在 native 代码中创建拷贝

r - 在管道 %>% 之后插入 if 语句以在自定义函数中返回错误消息