假设我有 2 个类(class) A
和 B
,其中 A
是一个纯抽象类,带有纯虚函数和 B
继承自 A
并实现纯虚函数。如果我有一个函数 g()
我想传递 A
的子类的任何实例按值到(这样我就可以在不改变原始实例的情况下改变它),你会怎么做?
我知道以下代码不符合我的目的:
void g(A myObject) {} //doesn't work since A contains a pure virtual function
void g(A* myObject) {} //code compiles, but changes the original instance
我会不会只是复制实例并创建一个指向它的指针并传递给像上面这样的函数?或者有没有更干净的方法来做到这一点?
最佳答案
我认为这里的最佳做法是利用 clone()
方法:
#include <iostream>
#include <memory>
class Base
{
public:
virtual void set_str(std::string) = 0;
virtual void print() = 0;
virtual std::unique_ptr<Base> clone() = 0;
};
class Derived: public Base
{
private:
std::string _str;
public:
std::unique_ptr<Base> clone() override {
return std::make_unique<Derived>(*this);
}
void set_str(std::string str) override {
this->_str = str;
}
void print() override {
std::cout << this->_str << std::endl;
}
};
void foo(std::unique_ptr<Base> obj) {
obj->set_str("inside");
obj->print();
}
int main() {
Derived obj;
obj.set_str("outside");
foo(obj.clone());
obj.print();
return 0;
}
关于c++ - 有没有办法将纯抽象类的所有子类按值传递给 C++ 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62714848/