C ++模板类复制构造函数和赋值运算符 [英] C++ template class copy-constructor and assignment-operator

查看:830
本文介绍了C ++模板类复制构造函数和赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板类Triple的实现,它是一个包含任何三种类型的容器。我的问题是,我的类接受三个const引用值作为参数,值必须是private(定义),但是,我还必须实现复制构造函数和重载赋值运算符。

I have an implementation of a template class Triple, which is a container holding any three types. My problem is that, my class takes three const references to values as parameter, and the values have to be private (definition), however, I also have to implement the copy-constructor and overloaded assignment operator.

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变量?

How would you implement the copy-constructor and assignment operator without assigning to const variables?

推荐答案

你可能不应该使用const引用作为成员,因为你不能(通常)知道对象的生命周期会超过你的生命周期对象, a b c Tx ,而不是 Tx const&

You should probably not have const references as members since you can't (in general) know that the objects lifetime will outlast the lifetime of your object, a, b and c should almost certainly be of type Tx and not Tx const&.

如果你知道这一点(确保你这样做,更有可能你不明白的意思,除非你是一个专家的C ++开发人员),那么你可以有一个复制构造函数使用初始化

If you do know this (be sure that you do, it's more probable that you don't understand the implications unless you're an expert C++ developer), then you can have a copy constructor using an initialization list.

Triple(const Triple& other) {
  : a(other.a)
  , b(other.b)
  , c(other.c)
{ }

你不能有赋值运算符,因为赋值给引用改变引用对象而不是引用,你可以模拟引用指针,但是因为我认为这不是你想要的,我不会拼写出来。

You can't have assignment operator since assigning to a reference changes the referred to object not the reference, you could simulate references with pointers but since I think this is not what you want I won't spell it out.

在任何情况下,真实的 应该是 正在使用 std :: tuple ,而不是重新发明轮子。

In any case the real thing you should be doing is using std::tuple and not reinventing The wheel.

这篇关于C ++模板类复制构造函数和赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆