我需要将一个对象(定义为接口(interface))传递给一个方法,但我不知道该怎么做。 该方法必须将此对象添加到 map 中。显然,传递的对象将是接口(interface) IFigure 的子对象。
void Drawing::addFigure(string id, IFigure figure) {
drawings.insert(id, figure);
}
Map 是这样定义的(在 Drawing 类中):
map<string,IFigure> drawings;
感谢您的宝贵时间!
最佳答案
您不能创建抽象类的实例。
所以声明:
IFigure figure;
这构造了一个新的 IFigure
.你不能那样做。
IFigure figure = Implementation{};
这也行不通。您正在创建一个新的 IFigure
通过复制切片 Implementation
.你也不能那样做。
变量是值,就像int
. IFigure figure
表示 IFigure
类型的值,而不是对实现的引用。它永远行不通。
切片有点像这样问:
int i = double{1.6};
std::cout << i;
// Why does it prints '1'?? I assigned '1.6', it should refer to it!
当然,会发生转换,因此它会丢弃 .6
部分。就像切片删除 Implementation
一样部分以仅保留基类部分。
那你能做什么呢??
您可以使用类似于引用的东西,这样您就可以拥有看起来像 IFigure
的东西。但实际上指向一个Implementation
.引用可以工作,但它们不是动态的,所以指针也可以。
// a pointer to base we tell to point it to this allocated implementation
std::unique_ptr<IFigure> figure = std::make_unique<Implementation>();
当使用类似 std::map
的容器时,你也可以像这样使用指针:
std::map<string,std::unique_ptr<IFigure>> figures;
每个元素看起来像这样带有值:
+--------+---------------+
| string | IFigure |
+--------+---------------+
带指针:
+------------------+
| Implementation |
+------------------+
^
|
+--------+--|---+
| string | ptr |
+--------+------+
然后像这样使用它:
figures.emplace("id1", std::make_unique<Implementation>());
// or
figures["id2"] = std::make_unique<Implementation>();
// or even
void Drawing::addFigure(std::string id, std::unique_ptr<IFigure> figure) {
// move ownership from 'figure' into 'drawings' so
// 'drawing' becomes the owner and 'figure' becomes null.
drawings.emplace(id, std:move(figure));
}
Why not
std::map<string, IFigure*>
? It look simpler.
如果您希望容器成为所有数据的所有者(当容器死亡时所有元素被销毁),那么指针将成为拥有者。使用拥有原始指针会带来很多初学者难以处理的问题。如果你使用 new
,可能存在错误,或者您有非常特殊的需求。
关于c++ - 如何将接口(interface)对象传递给方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57675300/