gpt4 book ai didi

c++ - 模板赋值运算符不会替换默认的赋值运算符

转载 作者:IT老高 更新时间:2023-10-28 23:13:36 25 4
gpt4 key购买 nike

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

Note that a template assignment operator doesn't replace the defaultassignment operator. For assignments of stacks of the same type, thedefault assignment operator is still called.

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

#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;
}

我得到答案 100 20。

它没有给出默认的作业答案。

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

C++ Templates: The Complete Guide By David Vandevoorde, Nicolai M.Josuttis

Publisher : Addison Wesley

Pub Date : November 12, 2002 Pages : 552

最佳答案

复制赋值运算符确实是隐式声明的,并由重载决议考虑。

A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X [..].

If the class definition does not explicitly declare a copy assignment operator, one is declared implicitly. [..] The implicitly-declared copy assignment operator for a class X will have the form

X& X::operator=(const X&)

if

  • each direct base class B of X has a copy assignment operator whose parameter is of type const B&, const volatile B& or B, and
  • for all the non-static data members of X that are of a class type M (or array thereof), each such class type has a copy assignment operator whose parameter is of type const M&, const volatile M& or M.

Otherwise, [..]

如您所见,Pair<int> 的隐式声明的复制赋值运算符有一个 Pair<int> const& 类型的参数- 注意 const尤其是!重载分辨率有利于非 const超过 const 的引用资料如果两者都可以绑定(bind)到参数,[over.ics.rank]/3:

Two implicit conversion sequences of the same form are indistinguishable conversion sequences unless one of the following rules applies:

— Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if

  • [..]
  • S1 and S2 are reference bindings (8.5.3), and the types to which the references refer are the same type except for top-level cv-qualifiers, and the type to which the reference initialized by S2 refers is more cv-qualified than the type to which the reference initialized by S1 refers.

模板的特化缺少const在引用参数中,因此它是一个更好的匹配并被选中。

关于c++ - 模板赋值运算符不会替换默认的赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27679002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com