2017-04-15 52 views
-2

我想重載ostream和istream作爲模板中的類的freind。我在網上看過,但一直沒能找到很多關於模板重載的內容,我所看到的似乎也表明這是裝載這些內容的方式。很顯然,我對編程非常陌生,希望得到任何幫助。謝謝。重載插入和提取操作符作爲模板

#include <stdio.h> 
#include<vector> 
#include<iostream> 
using namespace std; 
template<class T> 
class MyClass 

{ 
enter code here 
public: 
    MyClass(); 
    MyClass(const T& p_val1); 
    MyClass(const MyClass<T>& p_val1); 
    ~MyClass(); 
    MyClass<T>& operator=(MyClass<T>& rhs); 

    friend ostream& operator<<(ostream& lhs, const MyClass<T> &printme); 
    friend istream& operator>><T>(istream& lhs, MyClass<T>& readme); 

private: 
    T* m_val1; 

};

執行ostream和istream。

template<class T> 
ostream& operator<<(ostream&lhs, const MyClass<T>& printme) 
{ 
    lhs << printme.m_val1; 
    return lhs; 
} 
template<class T> 
istream& operator>>(istream& lhs, MyClass<T>& readme) 
{ 
    lhs >> *(readme.m_val1); 
    return lhs; 
} 

這裏有錯誤

Undefined symbols for architecture x86_64: 
    "MyClass<int>::~MyClass()", referenced from: 
     _main in main.o 
    "operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, MyClass<int> const&)", referenced from: 
     _main in main.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

主要功能

MyClass<int> a(8); 
    MyClass<int> b(9); 
    cout << " Enter a value for the two types to be swapped: "; 
    cin >> a >> b; 
    cout << "Before swapping...\n"; 
    cout << "Object a's pointer member dereferences a value of:\t" << a << endl; 
    cout << "Object b's pointer member dereferences a value of:\t" << b << endl; 
+0

請發佈您正在編譯的實際代碼。 –

回答

0

你可以聲明你的運營商,而不是定義它們。模板定義與您類內部的模板定義無關,因爲它們的原型不同,因此鏈接錯誤。你的宣言改成這樣:

template <typename T, typename Trait> 
friend std::basic_ostream<T, Trait>& 
operator<< (std::basic_ostream<T, Trait>& out, const MyClass& c) 
{ 
    return out << c.my_val1; 
} 

template <typename T, typename Trait> 
friend std::basic_istream<T, Trait>& 
operator>> (std::basic_istream<T, Trait>& in, MyClass& c) 
{ 
    return in >> *(c.my_val1); 
} 

注意,它使用std::basic_ostreamstd::basic_istream,各自的類型和類型特徵。它允許使用所有流,不僅可以使用std::ostreamstd::istream