C++输出运算符重载问题

来源:百度知道 编辑:UC知道 时间:2024/05/21 16:16:17
程序如下:
#include <iostream>
using namespace std;
template<class T>
class A{
T t;
public:
A(T m):t(m){};
friend ostream & operator <<(ostream & out , A<T>& a);
};
template<class T>
ostream & operator <<(ostream & out , A<T>& a){
out<<a.t<<endl;
return out;
};

int main(){
A<int> a(1);
cout<<a;
}

程序编译可以通过,链接是错误为:main.obj : error LNK2019: 无法解析的外部符号 "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class A<int> &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAV?$A@H@@@Z),该符号在函数 _main 中被引用
1>F:\study\C++\数据结构\线性表\Debug\线性表.exe : fatal error LNK1120: 1 个无法解析的外部命令
麻烦高手解答!!!
用vs2008编译的

你程序出错的主要原因是:你没有搞清楚什么是友元friend,他与class的关系又是什么~
简单的说就是:将一个函数声明为friend只是赋予这个函数具有访问class的私有成员和protected成员的权利而已,即只改变了函数的访问能力(权限)
在你的程序里:输出运算符只是一个普通的函数(不是模板函数)至于第二个参数A<T>& a则只在class内部起作用(即编译不会出错)
假如你现在要写一个成员函数,其中有一个参数是模板类对象的引用即(A& a)而非(A<T>& a),也就是说在类定义体内(化括弧)不会出现
A<T> 这种类型,除非定义友元的模板函数,但是此T非彼T(修改后的类里边其实有两种T(friend模板函数里边的T不是定义类模板是的那个T,前者只属于本函数,你也可以将T改成别的如Type,好好理解一下)
说的比较模糊,请见谅~~!
另外:你上面的程序虽然编译通过,但是有一个最好不要那样做(因为你在函数后面加了一个;)有与C++允许有空语句,即 ;什么也不做
。但是,这有何必呢?(你看江小石---回答问题者---就误解了,以为你的编译器有问题)
额外的编程规范就不说了(因为太多了,虽然你的代码很短),总之你写的代码不怎么规范(下面代码与你的“规范”保持一致),注意一下~
#include <iostream>
using namespace std;

template<class T>
class A{
T t;
public:
A(T m):t(m){}
template <class T>
friend ostream& operator << (ostream& out, A<T>& a);
};

template<class T>
ostream& operator <<(ostream& out ,A<T>& a)
{
out << a.t <