积少@成多 2018-12-03 15:00 采纳率: 0%
浏览 1460

模板类中重载<<运算符,声明在类中,定义在类外,编译错误。

#include
using namespace std;

template
class A{
friend A operator- (A& m, A&n){
A t(m.a - n.a, m.b - n.b);
return t;
}
friend ostream & operator<< (ostream &out, A &t);
public:
A(){

}
A (T a, T b);
A operator + (A &m);
void show();
private:
T a;
T b;

};

template
ostream & operator<< (ostream &out, A &t){
out << t.a << " + " << t.b << "i";
return out;
}

template
A::A (T a, T b){
this->a = a;
this->b = b;
cout << "init" << endl;
}

template
void A::show(){
cout << "a:" << a << "b:" << b << endl;
}

template
A A::operator+ (A &m){
A t(a + m.a, b + m.b);
return t;
}

int main(){
A t(1,2);
// cout << t << endl;
// A t2(3,4);
// A t3 = t + t2;
// cout << t3 << endl;
// t3 = t - t2;
// cout << t3 << endl;
return 0;
}

g++编译
t2.cpp: In instantiation of ‘class A’:
t2.cpp:48:10: required from here
t2.cpp:10:19: error: template-id ‘operator<< ’ for ‘std::ostream& operator<<(std::ostream&, A&)’ does not match any template declaration
friend ostream & operator<< (ostream &out, A &t);
^
init

  • 写回答

1条回答 默认 最新

  • devmiao 2018-12-03 15:55
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题