2017-04-15 10 views
-2

ostream 및 istream을 템플릿의 클래스의 freind로 오버로드하려고합니다. 나는 온라인으로 보았지만 템플릿 오버로딩을 지정하는 많은 것을 찾을 수 없었으며, 내가 보았던 것 또한 이것이 orevload하는 방법이라고 설명하고있다. 프로그래밍에 익숙하지 않고 도움이된다면 분명합니다. 고맙습니다.템플릿으로 삽입 연산자 및 추출 연산자 오버로드

#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

주요 기능. 템플릿 정의는 프로토 타입이 다르므로 클래스 내부의 템플릿 정의와 관련이 없으므로 링크 오류가 발생합니다. 이 귀하의 선언을 변경합니다 : 그것은 그들의 각각의 유형과 유형의 특성과, std::basic_ostreamstd::basic_istream를 사용하고 있음을

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::ostreamstd::istream뿐만 아니라 모든 스트림을 사용할 수 있습니다.