C++覆盖子类创建的对象的功能

标签 c++ inheritance overriding

我想知道是否可以在不创建全新类的情况下只覆盖类中的一个函数。

我希望 bObj1.foo(); 输出“foo!”和 bObj2.foo() 输出“foo?”,但目前它们都输出“foo!”。

#include <iostream>
using namespace std;

class B {
    public:
    virtual void foo() { cout << "foo!" << endl; }
};

class A {
    public:
    B f();
};

B A::f() {
    B bObj;
    return bObj;
}

class C : public A {
};

int main()
{
    A aObj;
    B bObj1 = aObj.f();
    bObj1.foo(); // "foo!"

    C cObj;
    B bObj2 = cObj.f();
    bObj2.foo(); // "foo?"
}

最佳答案

您可以通过简单的更改获得所需的行为,这包括将“虚拟”行为移至 A 和 C 类。

我在这里修改了您的应用程序以返回预期结果:

#include <iostream>
using namespace std;

class A;

class B {
public:
    B(A& a) : aref(a) {}
    void foo();
private:
    A& aref;
};

class A {
public:
    B f();
    virtual void foo() { cout << "foo!" << endl; }
};

B A::f() {
    B bObj(*this);
    return bObj;
}

class C : public A {
public:
    virtual void foo() { cout << "foo?" << endl; }
};

void B::foo() { aref.foo(); }

int main()
{
    A aObj;
    B bObj1 = aObj.f();
    bObj1.foo(); // "foo!"

    C cObj;
    B bObj2 = cObj.f();
    bObj2.foo(); // "foo?"
}

关于C++覆盖子类创建的对象的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7656962/

相关文章:

c++ - std::map 排序谓词按字符串大小排序但保留不同的字符串?

c++ - Bank Kattis 问题的算法正确性

.net - 以下场景的最佳设计模式

java - 为什么 onCommand 从未在插件中使用

matplotlib - 如何覆盖 mpl_toolkits.mplot3d.Axes3D.draw() 方法?

c++ - 为什么重载 area 函数时以下代码会出现歧义

c++ - 转到定义失败 - Visual Studio 2008

c++ - 为什么要为命令行应用程序包含 QtWidgets?

javascript - 继承和 TypeScript 错误 : X is not a constructor function type

python - "Partial Inheriting"来自 Django 模型