Osa*_*gie 1 c++ operator-overloading copy-constructor
我一直在尝试测试对我的结构的赋值运算符=的调用:
struct array{
void* data;
template<typename S, typename T>
array& operator= (const map<S, T>& that){ cout << "worked..."; return *this;}
private:
array(); //i don't need this
};
Run Code Online (Sandbox Code Playgroud)
我像这样试驾:
map<int, string> var;
array arr = var;
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
Error: conversion from
'std::map<int, string, std::less<int>, std::allocator<std::pair<const int, string> > >'
to non-scalar type 'array' requested*/
Run Code Online (Sandbox Code Playgroud)
问题:到底是什么问题?如何使这样的运算符超载?我的意思是
operator=,它应该将不同类型的对象转换为自己的类类型。
报关单
map<int, string> var;
array arr = var;
Run Code Online (Sandbox Code Playgroud)
…不调用副本分配运算符。
它使用(或表现为使用)复制构造函数:声明中=表示复制初始化。
如果该类具有其他构造函数,则将考虑将它们转换var为array实例,然后(除非对此部分进行了优化)将传递给副本构造函数。
但是,您只有默认的副本构造函数。
从类型B到类类型A的转换最好用以下两种方式之一表示:
通过类A接受B的构造函数。
如果B是一个类,则通过B operator A(转换运算符)进行。
在其他新闻中:
void*是一种丢弃类型信息的方法。丢弃类型信息是一种制造麻烦的方法。所以,void*最好避免。