Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用模板重载运算符_C++_Templates_Operator Overloading - Fatal编程技术网

C++ 使用模板重载运算符

C++ 使用模板重载运算符,c++,templates,operator-overloading,C++,Templates,Operator Overloading,我试图修改Add函数来表示运算符重载 #include <iostream> using namespace std; template <class T> class cpair { public: cpair(T x = 0, T y = 0) { A = x; B = y; } void print() { cout << A << " " << B << endl;

我试图修改Add函数来表示运算符重载

#include <iostream>
using namespace std;

template <class T>
class cpair
{
public:
    cpair(T x = 0, T y = 0) { A = x; B = y; }
    void print()
    {
        cout << A << " " << B << endl;
    }
    T A, B;
};

template <class T>
void Add(cpair<T> A1, cpair<T> A2, cpair<T> &R)
{
    R.A = A1.A + A2.A;
    R.B = A1.B + A2.B;
}

int main()
{
    cpair<int> A1(4, 5), A2(1, 3), result;
    Add(A1, A2, result);
    result.print();

    return 0;
}
#包括
使用名称空间std;
模板
类cpair
{
公众:
cpair(tx=0,ty0){A=x;B=y;}
作废打印()
{

cout您似乎误解了很多。首先,如果要重载加法运算符,则需要重载的是
运算符+
函数,而不是赋值运算符

要解决这个问题,你应该这样做

template <class T>
cpair<T> operator+(cpair<T> const& a, cpair<T> const& b)
{
    return cpair<T>(a.A + b.A, a.B + b.B);
}
那你会做的

r = a + b;
重载运算符也是如此:

cpair<int> a(4, 5), b(1, 3), result;
result = a + b;
cpair a(4,5),b(1,3),结果;
结果=a+b;
如果您想了解更多信息,我建议您。

模板
类cpair{
公众:
cpair和运算符+=(cpair常量和o)&{
A+=o.A;
B+=o.B;
归还*这个;
}
友元cpair运算符+(cpair左侧、cpair常量和右侧){
lhs+=rhs;
返回lhs;
}
//...

上面是在模板类上重写
+
的标准方法。

void operator=
应该是
void cpair::operator=
,这就是错误消息在提到“成员函数”时所指的内容作为一个成员,它应该只接受一个参数,你不应该随意添加另一个参数。它注定要失败。
r = a + b;
cpair<int> a(4, 5), b(1, 3), result;
result = a + b;
template <class T>
class cpair {
public:
  cpair& operator+=( cpair const& o )&{
    A+=o.A;
    B+=o.B;
    return *this;
  }
  friend cpair operator+( cpair lhs, cpair const& rhs ){
    lhs+=rhs;
    return lhs;
  }
//...