템플릿 클래스를 .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;
}
유형 :
은 템플릿과 같이operator<<
을cout
변화 비 템플릿 클래스와 클래스의 드롭 인 교체로 사용하려면 다시 출력합니다. 이 경우'const char *'가 작동해야한다. 그러나 템플리트 [.h와 .cpp 파일 사이에서 분리] (https://stackoverflow.com/q/495021/10077)에 어려움이있을 것입니다. –또한 헤더 파일에서'using namespace std;'를 사용하면 [가증 스럽습니다] (https://stackoverflow.com/q/1452721/10077). –