gpt4 book ai didi

c++ - C++中重写虚方法

转载 作者:行者123 更新时间:2023-11-28 03:41:00 24 4
gpt4 key购买 nike

我有一个包含很多类的库。我想修改某个类的一个虚方法的行为。我试图简化我所拥有的,这里是:

#include <iostream>  

using namespace std;

class B;

class A {
public:
A(B& b_) : b(b_) {};

B& b;

virtual void printon() {
cout << "Test virtual printon A\n" << endl;
}
void print() {
cout << "Test print A\n";
printon();
}
};

class B {
protected:
A a;
public:
B() : a(*this) {};

void print() {
a.print();
};
};

在我的程序中,我可以像这样使用它:

int main()   {  
B* b = new B();
b->print();
return 0;
}

实际上方法 a.printon() 是从一些其他代码和不同条件下调用的,并且不打印任何内容(它执行一些其他操作)。我需要覆盖此方法来做其他事情,例如打印“test2”。

我可以创建派生类newA:

class newA : public A {  
public:
newA(B& b_) : A(b_) {};

virtual void printon() {
cout << "Test printon newA"<< endl;
}
};

我不确定下一步该做什么。也许创建一个类 newB,例如:

class newB : public B {
public:
newB() : B() {};
};

但是如何让 A 类型的 B.a 表现得像 newA 类型呢?

最佳答案

B 按值包含 A,这排除了多态性的使用(如果您尝试将 newA 设置为 A 对象,你得到对象切片。如果你希望你的 B 能够使用 A 的派生版本,你需要通过(智能)存储它指针。

关于c++ - C++中重写虚方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9272402/

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