テンプレートクラスを.hファイルに定義しました。ostreamクラスを持つコンストラクタを定義しています。私はメインでどのようにコンストラクタを使用するかはわかりません。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
た.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;
}
種類のタイプ、あなたのようになります。ドロップイン置換非テンプレートクラスにクラスを変更し、これは以下のようにちょうど
operator<<
テンプレート作るcout
用として使用する出力しています。この場合、 'const char *'は動作するはずです。しかし、あなたはあなたのテンプレート[.hと.cppファイルの間で分割](https://stackoverflow.com/q/495021/10077)に苦労するでしょう。 –
また、ヘッダーファイルで 'using namespace std;'を使用することは忌み嫌いです(https://stackoverflow.com/q/1452721/10077)。 –