2017-09-28 22 views
0

템플릿 클래스를 .h 파일에 정의했으며 ostream 클래스를 갖는 생성자를 정의합니다. main에 생성자를 사용하는 방법에 대해서는 매듭을 짓지 않습니다.C++ 템플릿 함수를 사용하여 주 함수에 ostream 클래스 변수가있는 생성자를 정의하십시오.

원래 스트림의 ASCII 코드를 합쳐서 입력하고 싶습니다. 각 유형의 변수에 대해 쓰는 대신 템플릿 클래스를 사용해야합니다.

.H 파일

#ifndef SPYOUTPUT_H 
#define SPYOUTPUT_H 
#include <iostream> 
using namespace std; 
template <class T> 
class SpyOutput { 
    int Count, CheckSum; 
    ostream* spy; 
public: 
    int getCheckSum(); 
    int getCount(); 

    ~SpyOutput(); 
    SpyOutput(ostream* a); 
    SpyOutput & operator << (T val); 
} 
#endif 

통화 당

template <class T> 
SpyOutput<T>::SpyOutput(std::ostream* a) { 
    spy = a; 
    Count = 0; 
    CheckSum = 0; 
} 

template <class T> SpyOutput<T>::~SpyOutput() {} 

template <class T> SpyOutput<> & SpyOutput<T>::operator << (T val) { 
    stringstream ss; 
    ss << val; 
    string s; 
    s = ss.str(); 
    *spy << s; 
    Count += s.size(); 
    for (unsigned int i = 0; i < s.size(); i++) { 
     CheckSum += s[i]; 
    } 
    return *this; 
} 

template <class T> 
int SpyOutput<T>::getCheckSum() { 
    return CheckSum; 
} 

template <class T> 
int SpyOutput<T>::getCount() { 
    return Count; 
} 

MAIN.CPP

#include "SpyOutput.h" 
#include <iostream> 
#define endl '\n' 

int main() 
{ 
    double d1 = 12.3; 
    int i1 = 45; 
    SpyOutput spy(&cout); // error agrument list of class template is missing 
    /* 
    template <class T> SpyOutput<T> spy(&cout); // not working error 
    SpyOutput<ostream> spy(&cout); 
    // not working error having error on operator <<not matches with these oprands 
    */ 

    spy << "abc" << endl; 
    spy << "d1=" << d1 << " i1=" << i1 << 'z' << endl; 

    cout << "count=" << spy.getCount() << endl; 
    cout << "Check Sum=" << spy.getCheckSum() << endl; 
    return 0; 
} 
+0

유형 :

은 템플릿과 같이 operator<<cout 변화 비 템플릿 클래스와 클래스의 드롭 인 교체로 사용하려면 다시 출력합니다. 이 경우'const char *'가 작동해야한다. 그러나 템플리트 [.h와 .cpp 파일 사이에서 분리] (https://stackoverflow.com/q/495021/10077)에 어려움이있을 것입니다. –

+0

또한 헤더 파일에서'using namespace std;'를 사용하면 [가증 스럽습니다] (https://stackoverflow.com/q/1452721/10077). –

답변

1

당신은 함수 템플릿과 클래스 템플릿의 사용을 혼합하고 있습니다. 올바르게 이해하면 cout 주위에 래퍼를 만들려고하는데 다른 유형과 함께 사용하려면 operator<< 템플릿을 사용해야합니다. 지금 당신은 다른 유형을 위해 템플릿 화 된 클래스를 선언합니다.

의 차이는 인쇄 할 때 지금 당신이 (기껏해야 지루한 것이다) 적절한 래퍼 인스턴스를 등등 intcharfloat 및 별도의 래퍼를 작성해야합니다 ... 그리고 사용하는 것입니다. 템플릿 인스턴스화는 유형이 될 것입니다 제공하기 위해

#ifndef SPYOUTPUT_H 
#define SPYOUTPUT_H 

#include <iostream> 

class SpyOutput { 
    int Count, CheckSum; 
    std::ostream* spy; 
public: 
    int getCheckSum(); 
    int getCount(); 

    ~SpyOutput(); 
    SpyOutput(std::ostream* a); 
    template <class T> 
    SpyOutput & operator << (T val) { 
     // here copy the implementation from .cpp 
     // so that template is instantiated for 
     // each type it is used with 
    } 
} 
#endif