【发布时间】:2020-03-01 15:13:36
【问题描述】:
考虑以下场景:
class AbsBase {
public:
virtual double foo() = 0;
};
class Concrete1 : public AbsBase {
public:
double foo() {
return 1;
}
};
class Concrete2 : public AbsBase {
public:
double foo() {
return 2;
}
};
struct Config {
/**
* Must use a pointer to `AbsBase`, since it is an abstract base class,
* and the concrete instances could be of either of the derived classes.
*/
AbsBase* thing;
void setThing(AbsBase* t) {
thing = t;
}
};
这工作,但如果thing 是传递给setThing 的参数的副本,我会更喜欢它。 IE。如果thing 是Concrete1 类型(而不是抽象基类),我可以这样做:
Concrete1 thing;
void setThing(const Concrete1& t) {
thing = Concrete1(t);
}
但是,如果不实例化抽象类型的对象(这是非法的),我看不到实现此目的的方法。有什么想法吗?
【问题讨论】:
-
您可以尝试通过声明
thing来使其成为引用:AbsBase &thing。 -
否则我只是看不出你想要什么是可能的,因为它甚至没有意义。
-
但是通过引用传递不会复制对象
-
@marvinIsSacul 这将消除更改它所指对象的可能性。
-
但是这样想,你怎么能创建一个不存在的东西的副本(抽象类型)?
标签: c++ abstract-class base-class