模板,运算符重载,友员

#include <iostream>
using namespace std;

template <typename T>
class A {
public:
    T x, y;
public:
    A<T> operator-(const A<T> &t);

    template<typename T>
    friend A<T> operator+(const A<T> &x, const A<T> &y);
public:
    A();
    A(T t);
};

template <typename T>
A<T> A<T>::operator-( const A<T> &t )
{
    A<T> z;
    z.x = x + t.x;
    z.y = y + t.y;
    return z;
}

template<typename T>
A<T>::A()
{
}


template<typename T>
A<T>::A(T t)
 {
    x = t;
    y = t;
}


template<typename T>
A<T> operator+(const A<T> &x, const A<T> &y) {
    A<T> z;
    z.x = x.x + y.x;
    z.y = x.y + y.y;
    return z;
}

int main() {
    A<double> a = 1;        // 正确编译运行
    A<double> b = a + A<double>(1);    // 显示调用正确
    //A<double> c = a + 1; // 友员隐式调用就会出错
    A<double> d = a - 1;    // 成员隐式调用不会出错
    system("pause");
}
原文地址:https://www.cnblogs.com/litstrong/p/2790911.html