[英]C++ using template function, define a constructor having ostream class variable in main function
我已經在.h文件中定義了模板類,它包括定義具有ostream類的構造函數。 我不知道如何在main中使用構造函數。
最初,我想對輸入流的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
的.cpp
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;
}
您正在混合使用類模板和函數模板。 如果我正確理解,您想在cout
周圍創建包裝器,該包裝器將具有模板化operator<<
以與任何其他類型一起使用。 現在,您聲明為任何其他類型模板化的類。
所不同的是,現在您需要為int
和char
和float
等創建單獨的包裝器,並在打印時使用適當的包裝器實例(充其量是乏味的)。
要將其用作cout
替代產品,請將您的類更改為非模板類,並僅使operator<<
的模板如下所示:
#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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.