相关疑难解决方法(0)

模板赋值运算符不替换默认赋值运算符

C++模板中完整指南第5.3节"成员模板":

请注意,模板赋值运算符不会替换默认赋值运算符.对于相同类型堆栈的分配,仍会调用默认赋值运算符.

这是正确的,因为当我在代码下面运行时:

#include<iostream>
using namespace std;

template<typename T>
class Pair
{
    public:
            T pair1,pair2;
            Pair(T i,T j):pair1(i),pair2(j){}
            template<typename T1>Pair<T>& operator=(Pair<T1>&);             
};

template<typename T>
template<typename T1>
Pair<T>& Pair<T>::operator=(Pair<T1>& temp)
{

    this->pair1 =temp.pair1*10;//At this point
    this->pair2=temp.pair2;
    return *this;
}

int main()
{

    Pair<int>P1(10,20);
    Pair<int>P2(1,2);
    P2=P1;
    cout<<P2.pair1<<' '<<P2.pair2<<endl;
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

我得到了答案100 20.

它没有给出默认的分配答案.

这是C++模板完整指南中的输入错误吗?

C++模板:完整指南作者:David Vandevoorde,Nicolai M. Josuttis

出版商:Addison Wesley

发布日期:2002年11月12日ISBN:0-201-73484-2页数:552

c++ templates

12
推荐指数
2
解决办法
1690
查看次数

模板赋值运算符重载神秘

我有一个简单的结构Wrapper,由两个模板化赋值运算符重载区分:

template<typename T>
struct Wrapper {

  Wrapper() {}

  template <typename U>
  Wrapper &operator=(const Wrapper<U> &rhs) {
    cout << "1" << endl;
    return *this;
  }
  template <typename U>
  Wrapper &operator=(Wrapper<U> &rhs) {
    cout << "2" << endl;
    return *this;
  }
};
Run Code Online (Sandbox Code Playgroud)

然后我宣布a和b:

Wrapper<float> a, b;
a = b;
Run Code Online (Sandbox Code Playgroud)

分配ba将使用非const模板赋值操作过载从上方和数字"2"被显示.

令我困惑的是:如果我宣布cd,

Wrapper<float> c;
const Wrapper<float> d;
c = d;
Run Code Online (Sandbox Code Playgroud)

并且分配dc,既没有使用两个赋值运算符重载,也没有显示输出; 因此调用默认的复制赋值运算符.为什么分配dc未使用const重载赋值操作符提供?或者相反,为什么分配ba …

c++ templates assignment-operator

7
推荐指数
2
解决办法
5632
查看次数

标签 统计

c++ ×2

templates ×2

assignment-operator ×1