c++ - 如何将接口(interface)对象传递给方法?

标签 c++ dictionary methods interface

我需要将一个对象(定义为接口(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/

相关文章:

c# - 这些默认参数的人造模拟之间是否存在显着的机械差异?

c++ - 哪个链接更快?许多小的 .so 文件还是几个大的 .so 文件?

javascript 无法将元素添加到字典中

python - 定义一个字典,其名称已作为字符串存储在脚本中

java - 有没有更好的方法来为 java 编写这段代码?还是让它更干净?

html - 在 get 方法中使用图像作为输入字段

c++ - 构造函数的多重定义

c++ - C++中的移动构造函数和复制构造函数

c++ - 保存 wxWidgets 窗口截图

python - 抽认卡抛硬币词典