两则c++代码的语法问题

来源:百度知道 编辑:UC知道 时间:2024/05/09 03:42:10
看下为什么错了?编译出错语句已表明。
#include<iostream>
using namespace std;
template<class T>
class ap{
public:
ap(T* contain):apo(contain){}
T* operator->(){return apo;}
ap& operator=(ap copys){*apo=*(copys.apo);return *this;}
~ap(){delete apo;}
friend ostream& operator<<(ostream& ,const ap<T>& );//编译错误
protected:
T* apo;
private:
ap();
};
template<class T>
ostream& operator<<(ostream& oup,const ap<T>& ap0)
{oup<<*ap0.apo;return oup;}
main(){
ap<int> ap1(new int(19));
ap<int> ap2(new int(29));
ap1=ap2;
cout<<ap2;
system("pause");
}

直接在声明的时候定义友元模板函数

friend ostream & operator<< (ostream & oup, const ap< T > &ap0)
{
oup << *ap0.apo;
return oup;
}

类AP之前先声明operator<<

错误在函数体的定义部份:
ostream& operator<<(ostream& oup,const ap<T>& ap0)
{
oup<<*ap0.apo;
return oup;
}
形参中的&表示这个形式是引用,不是取地址,所以在使用形参时,不要用*ap0,改成oup<<ap0.apo;即可