我是模板编码的初学者,在模板中定义构造函数时遇到问题,只是寻找相关答案但找不到相关问题。
基本上,类/结构 xpair
类似于 pair
,它有 first
和 second
。
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 First& first_, const Second& second_) {
return new xpair (first_, second_);
}
xpair& operator= (const xpair& that) {
return new xpair (that.first, that.second);
}
};
当我想写类似的东西时
xpair<string, string> a, b;
a = b;
它给出错误为
non-const lvalue reference to type
'xpair<std::__1::basic_string<char>, std::__1::basic_string<char> >'
cannot bind to a temporary of type 'xpair<std::__1::basic_string<char>,
std::__1::basic_string<char> > *'
我试过重写
return new xpair (that.first, that.second);
到
return new pair (const_cast<First&>(that.first), const_cast<First&>(that.second));
但它不起作用。问题出在哪里?
最佳答案
删除 new
。这不是 Java!
在 C++ 中,new
是您未使用的动态分配(评估为指针)的关键字。
您还必须重新考虑按引用返回的语义,因为您将返回对局部变量的引用。这会产生一个悬挂引用。
事实上,您的语义总体上对我来说很奇怪。例如,为什么 operator=
实际上没有修改被分配给的对象?您应该将 that
分配给 *this
的成员,然后返回对 *this
的引用(或者至少返回 void
)。
我不知道你的 operator()
应该做什么——应该是一个构造函数吗?嗯,不,你已经有了其中之一……:(
我强烈建议您查看一些运算符重载示例,以便更好地理解 C++ 的构造和约束,以及我们的习惯用法和首选语义。
关于C++ - 在模板中定义复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35281670/