gpt4 book ai didi

C++ 派生函数与基函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:56:07 26 4
gpt4 key购买 nike

有没有一种方法可以在从基类派生的类上调用基类的成员函数?

Class Bass{
public:
void func();
};

Class Derived: public Base{
public:
void func();
};

我有一个期中练习,但我怀疑没有,因为 Base 类如何知道 Derived,但我不确定。

最佳答案

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com