C – 模板中的复制分配操作符
发布时间:2020-12-16 10:01:32 所属栏目:百科 来源:网络整理
导读:我正在尝试在模板struct xpair中重载一个复制赋值运算符 template typename First,typename Secondstruct xpair { First first{}; Second second{}; xpair(){} xpair (const First first,const Second second): first(first),second(second) {} xpair operat
我正在尝试在模板struct xpair中重载一个复制赋值运算符
template <typename First,typename Second> struct xpair { First first{}; Second second{}; xpair(){} xpair (const First& first,const Second& second): first(first),second(second) {} xpair& operator= (const xpair& that) { cout << "*this = " << *this << " " << "that = " << that << endl; cout << "use operator = " << endl; *this = that; return *this; } }; 但是当我用这个代码测试时 using commend = string; using str_str_pair = xpair<string,string>; using commend_pair = xpair<commend,str_str_pair>; commend_pair cmd_pair; str_str_pair str_pair("a","1"); commend cmd("comment"); cmd_pair.first = cmd; cmd_pair.second = str_pair; 它给了我无限的输出 use operator = *this = {,} that = {a,1} use operator = *this = {,1} 这是为什么? 解决方法
因为您已根据自身定义了该函数,请参阅以下代码注释. xpair& operator= (const xpair& that) { cout << "*this = " << *this << " " << "that = " << that << endl; cout << "use operator = " << endl; // Here you're asking for `this` (i.e.,an `xpair` type) to be assigned // a `that` (i.e.,another `xpair` type) using the `operator=` which is // the function currently being implemented/defined. A function calling // itself is recursion and there is no stopping condition so it will // continue infinitely. *this = that; return *this; } 相反,您的操作应使用该实例的数据成员设置此实例的数据成员. xpair& operator= (const xpair& that) { cout << "*this = " << *this << " " << "that = " << that << endl; cout << "use operator = " << endl; first = that.first; second = that.second; return *this; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |