注册 登录
编程论坛 C++教室

类摸板和重载<操作符的问题,求助 。

wuyun8536 发布于 2009-07-23 10:27, 358 次点击
前几天在这个论坛上看的一个程序!编译没有问题,链接时出现问题:
Linking...
D:\MinGWStudio\Templates\w\Debug\w.o(.text+0x9b): In function `main':
D:\MinGWStudio\Templates\w\w.cpp:48: undefined reference to `operator<<(std::ostream&, Vec3<double> const&)'

程序如下:

w.exe - 1 error(s), 0 warning(s)
#include<iostream>
using namespace std;

template<typename W>
 class Vec3;
    
template<typename U>
 ostream& operator<<(ostream&,const Vec3<U>&);

template<typename T>
 class Vec3
{
private:
    T x;
    T y;
    T z;
public:
    T GetX()const{return x;}
    T GetY()const{return y;}
    T GetZ()const{return z;}
   
    Vec3<T>(T a,T b,T c):x(a),y(b),z(c){}
    friend ostream& operator<<(ostream&,const Vec3<T>&);
    friend Vec3<T> operator+(Vec3<T>& x,Vec3<T>& r);

};

  template<typename T>
  ostream& operator<<(ostream& out,const Vec3<T>& r)
    {
           out<<"("<<r.GetX()<<","<<GetY()<<","<<GetZ()<<")";
           return out;
    }
  
  template<typename T>
  Vec3<T> operator+(Vec3<T>& x,Vec3<T>& r)
    {
     Vec3<T> a;
     a.x=x.GetX()+r.GetX();
     a.y=x.GetY()+r.GetY();
     a.z=x.GetZ()+r.GetZ();
      return a;
    }
int main()
{
    Vec3<double> a(1,2,3);
    Vec3<double> b(3,4,5);
    cout<<a;
    return 0;
}
2 回复
#2
ET_bug2009-07-23 10:37
类模板的问题看的我也头大...
看提示好像是未定义的引用operator<<(std::ostream&, Vec3<double> const&)
我也不太懂,希望有高手帮帮LZ
#3
cxn88012009-07-23 17:34
...
#include<iostream>
using namespace std;

template<typename T>
class Vec3
{
   friend ostream& operator<<(ostream& out ,  Vec3<T>& r)
   {
     out<<"("<<r.GetX()<<","<<r.GetY()<<","<<r.GetZ()<<")"<<endl;
     return out;
   }
   
   friend   Vec3<T> operator+( Vec3<T>& x, Vec3<T>& r)
   {
     Vec3<T> a;
     a.x=x.GetX()+r.GetX();
     a.y=x.GetY()+r.GetY();
     a.z=x.GetZ()+r.GetZ();
     return a;
   }

   public:
      Vec3(T a,T b,T c)
         :x(a),y(b),z(c){}
         
      T GetX()
      {
         return x;
      }
      T GetY()
      {
         return y;
      }
      T GetZ()
      {
         return z;
      }
   
     private:
        T x;
        T y;
        T z;

};


   
int main()
{
    Vec3<int> a(1,2,3);
    Vec3<double> b(3,4,5);
    cout<<a;
    return 0;
}
1