- 论坛徽章:
- 0
|
10可用积分
本帖最后由 songweibo 于 2012-06-10 12:56 编辑
我用VC8编译下面的代码提示错误:
- #include "stdafx.h"
- class my{
- public:
- my():i(2),j(3){printf("ctor\n");}
- ~my(){printf("dtor\n");}
- template<class T>
- vod add( T t ){
- i+=t;
- }
- private
- int i,j;
- };
- int main(int argc,char**){
- my m1;
- m1.add<short>(3);
- return 0;
- }
复制代码 提示我有一堆错误:
1>my.cpp(9): error C2146: syntax error : missing ';' before identifier 'add'
1>my.cpp(9): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>my.cpp(9): error C2238: unexpected token(s) preceding ';'
1>my.cpp(11): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>my.cpp(11): error C2143: syntax error : missing ';' before '<end Parse>'
1>my.cpp(11): warning C4183: 'add': missing return type; assumed to be a member function returning 'int'
1>my.cpp(13): error C2238: unexpected token(s) preceding ';'
1>my.cpp(5): error C2614: 'my' : illegal member initialization: 'j' is not a base or member
1>my.cpp(5): error C2614: 'my' : illegal member initialization: 'i' is not a base or member
1>my.cpp(17): error C2065: 'm1' : undeclared identifier
1>my.cpp(17): error C2062: type 'short' unexpected
如果我在class 前面加上模板声明
template<class U>
使用的时候变成 my<int> m1;
这次错误更多了
1>my.cpp(9): error C2146: syntax error : missing ';' before identifier 'add'
1> my.cpp(14) : see reference to class template instantiation 'my<U>' being compiled
1>my.cpp(9): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>my.cpp(9): error C2238: unexpected token(s) preceding ';'
1>my.cpp(9): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>my.cpp(9): error C2143: syntax error : missing ';' before '<end Parse>'
1>my.cpp(9): warning C4183: 'add': missing return type; assumed to be a member function returning 'int'
1>my.cpp(13): error C2238: unexpected token(s) preceding ';'
1>my.cpp(9): error C2146: syntax error : missing ';' before identifier 'add'
1> my.cpp(16) : see reference to class template instantiation 'my<U>' being compiled
1> with
1> [
1> U=int
1> ]
1>my.cpp(9): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>my.cpp(9): error C2238: unexpected token(s) preceding ';'
1>my.cpp(9): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>my.cpp(9): error C2143: syntax error : missing ';' before '<end Parse>'
1>my.cpp(9): warning C4183: 'add': missing return type; assumed to be a member function returning 'int'
1>my.cpp(13): error C2238: unexpected token(s) preceding ';'
到底错在哪里呢? |
最佳答案
查看完整内容
#include "stdafx.h"class my{public: my():i(2),j(3){printf("ctor\n");} ~my(){printf("dtor\n");} template void add( T t ){ i+=t; }private: int i,j;};int main(int argc,char** argv){ my m1; m1.add(3); return 0;}
|