C++模板类复制构造函数和赋值运算符
C++ template class copy-constructor and assignment-operator
我有一个模板类Triple的实现,它是一个包含任意三种类型的容器。我的问题是,我的类将对值的三个常量引用作为参数,并且值必须是私有的(定义),但是,我还必须实现复制构造函数和重载赋值运算符。
template <typename T1, typename T2, typename T3>
class Triple
{
public:
Triple()
{ }
Triple(const T1 &a, const T2 &b, const T3 &c) : a(a), b(b), c(c)
{ }
// copy constructor
Triple(const Triple &triple) {
a = triple.first();
b = triple.second();
c = triple.third();
}
// assignment operator
Triple &operator=(const Triple& other) {
//Check for self-assignment
if (this == &other)
return *this;
a = other.first();
b = other.second();
c = other.third();
return *this;
}
private:
T1 const& a;
T2 const& b;
T3 const& c;
};
如何在不赋值 const 变量的情况下实现复制构造函数和赋值运算符?
您可能不应该将 const 引用作为成员,因为您(通常)无法知道对象的生存期将超过对象的生存期,a
、b
和c
几乎肯定应该是 Tx
类型而不是Tx const&
。
如果您确实知道这一点(请确保您知道,除非您是专家C++开发人员,否则您很可能不了解其含义),那么您可以使用初始化列表拥有一个复制构造函数。
Triple(const Triple& other) {
: a(other.a)
, b(other.b)
, c(other.c)
{ }
你不能有赋值运算符,因为分配给引用会更改引用的对象而不是引用,你可以用指针模拟引用,但由于我认为这不是你想要的,所以我不会详细说明。
无论如何,你应该做的真正事情是使用std::tuple
而不是重新发明轮子。
相关文章:
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- 为用户定义的类正确调用复制构造函数/赋值运算符
- C++:关于使用 Stroustrup 示例移动构造函数/赋值的问题
- 初始值设定项列表与构造函数赋值与变量定义
- std::vector::emplace() 真的在面对抛出移动构造函数/赋值运算符时提供了强大的异常保证吗?
- 创建一个类并在C++中使用构造函数(赋值)
- 如何为具有自引用指针的类实现复制构造函数/赋值运算符
- 使typedef的构造函数/赋值运算符成为友元函数
- 复制构造函数+赋值运算符
- C++ 矢量从构造函数赋值对象,无需临时
- 具有std::原子成员变量的类的复制构造函数/赋值运算符出错
- 初始化对象时复制构造函数/赋值运算符混淆
- 默认情况下是默认的构造函数/赋值noexcept/constexpr
- 是否为派生类生成的移动构造函数/赋值运算符
- 复制构造函数/赋值运算符
- C++复制构造函数/赋值运算符错误
- 正在获取要使用的移动构造函数/赋值运算符
- 私有复制构造函数/赋值运算符和复制初始化
- 如何为自定义字符串类型编写构造函数/赋值运算符重载
- 为什么C++允许在具有指针成员的类中编译默认的复制构造函数/赋值运算符重载