[英]Error: expected type-specifier before Class
I am a java dev, learning c++. 我是一个Java开发人员,正在学习c ++。 This following sample code doesn't compile and I couldn't find a clue. 以下以下示例代码无法编译,我也找不到任何线索。
#include <iostream>
#include <cstdlib>
#include <string>
#include <stdexcept>
using namespace std;
template <class T>
class MyObj {
public:
T value;
MyObj(T a){
this.value = a;
}
};
template <class T>
inline MyObj<T> const& sum(MyObj<T> const& a, MyObj<T> const& b)
{
// append copy of passed element
T result = a.value+b.value;
MyObj<T> obj = new MyObj(result);
return obj;
}
int main()
{
try {
MyObj<int> s1 = new MyObj(1);
MyObj<int> s2 = new MyObj(3);
MyObj<int> s3 = sum(s1,s2);
cout << s3.value <<endl;
}
catch (exception const& ex) {
cerr << "Exception: " << ex.what() <<endl;
return -1;
}
}
It returns - 它返回-
main.cpp:31:29: error: expected type-specifier before 'MyObj' MyObj s1 = new MyObj(1); main.cpp:31:29:错误:'MyObj'之前的预期类型说明符MyObj s1 = new MyObj(1);
and 和
main.cpp:32:29: error: expected type-specifier before 'MyObj' MyObj s2 = new MyObj(3); main.cpp:32:29:错误:'MyObj'之前的预期类型说明符MyObj s2 = new MyObj(3);
Any help would be appreciated. 任何帮助,将不胜感激。
With new
you are allocating memory on the heap, and so you need a pointer to point to that newly allocated memory: MyObj<int>* s1 = new MyObj(1);
使用new
您正在堆上分配内存,因此需要一个指针指向该新分配的内存: MyObj<int>* s1 = new MyObj(1);
Next, MyObj
is a template class, so you have to specify T
when you call the construtor: MyObj<int>* s1 = new MyObj<int>(1);
接下来, MyObj
是模板类,因此在调用MyObj<int>* s1 = new MyObj<int>(1);
时必须指定T
: MyObj<int>* s1 = new MyObj<int>(1);
Because s1
and s2
are now pointers, sum
can't accept them as pointers, you have deference them to get the values: sum(*s1, *s2);
因为s1
和s2
现在是指针,所以sum
不能将它们接受为指针,因此请尊重它们以获取值: sum(*s1, *s2);
As @rgettman pointed out, this
is a pointer, and so must be acessed using ->
and not .
正如@rgettman指出的那样, this
是一个指针,因此必须使用->
而不是.
. 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.