|
楼主 |
发表于 2005-12-19 12:37:48
|
显示全部楼层
呃,是我没说清楚.是作为模板类的友员.
[PHP]
//testTempClass.h
#include <iostream>
using namespace std;
#ifndef H_testTempClass
#define H_testTempClass
template<class Type>
class testClass
{
friend ostream& operator<<
(ostream& osObj, const testClass<Type> &rightObj);
public:
void setData(Type elem);
private:
Type a;
};
template <class Type>
ostream& ostream& operator<<
(ostream& osObj, const testClass<Type> &rightObj)
//原来的testClass后面没有<Type>
{
osObj<<rightObj.a;
return osObj;
}
template <class Type>
void testClass<Type>::setData(Type elem)
{
a = elem;
}
#endif
//main.cpp
#include "testTempClass.h"
int main()
{
testClass<int> intObj;
intObj.setData(2);
cout<<intObj;
cout<<endl;
return 0;
}
[/PHP]
- $ g++ -o test main.cpp
- In file included from main.cpp:3:
- testTempClass.h:13: warning: friend declaration `std::ostream&
- operator<<(std::ostream&, const testClass<Type>&)' declares a non-template
- function
- testTempClass.h:13: warning: (if this is not what you intended, make sure the
- function template has already been declared and add <> after the function
- name here) -Wno-non-template-friend disables this warning
- testTempClass.h:21: error: syntax error before `&' token
- testTempClass.h:22: error: `Type' was not declared in this scope
- testTempClass.h:22: error: template argument 1 is invalid
- testTempClass.h:24: error: ISO C++ forbids declaration of `operator<<' with no
- type
- testTempClass.h:24: error: ISO C++ forbids declaration of `rightObj' with no
- type
- testTempClass.h: In function `int& operator<<(std::ostream&, const int&)':
- testTempClass.h:25: error: request for member `a' in `rightObj', which is of
- non-class type `const int'
- testTempClass.h:26: error: invalid initialization of reference of type 'int&'
- from expression of type 'std::basic_ostream<char, std::char_traits<char> >'
复制代码
还是错误,呵呵. 请大家多多指教.. |
|