码迷,mamicode.com
首页 > 其他好文 > 详细

[基础] 模板+友元类外定义

时间:2016-03-11 01:16:32      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

下面这种定义方式会报错: Undefined symbols for architecture x86_64

template <typename T>
class longint{
public:
    T num;
    longint (T a = 0) {
        num = a;
    }
    
    friend ostream& operator<< (ostream& out, const longint<T>& Lint);
    ~longint (){
        ;
    }
private:
};

template <typename T>
ostream& operator<< (ostream &out, const longint<T> & Lint) {
    return out<<Lint.num;
}

改法一:将重载运算符的T改成S就行了

//类内声明时
template <typename S>
friend ostream& operator<< (ostream& out, const longint<S>& Lint);

//类外定义时
template <typename S>
ostream& operator<< (ostream &out, const longint<S> & Lint) {
    return out<<Lint.num;
}

改法二:直接在类内定义

friend ostream& operator<< (ostream& out, const longint<T>& Lint) {
    return out<<Lint.num;
}

 

[基础] 模板+友元类外定义

标签:

原文地址:http://www.cnblogs.com/littletail/p/5264122.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!