繁体   English   中英

错误:上课前应有类型说明符

[英]Error: expected type-specifier before Class

我是一个Java开发人员,正在学习c ++。 以下以下示例代码无法编译,我也找不到任何线索。

#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;
    } 
} 

它返回-

main.cpp:31:29:错误:'MyObj'之前的预期类型说明符MyObj s1 = new MyObj(1);

main.cpp:32:29:错误:'MyObj'之前的预期类型说明符MyObj s2 = new MyObj(3);

任何帮助,将不胜感激。

使用new您正在堆上分配内存,因此需要一个指针指向该新分配的内存: MyObj<int>* s1 = new MyObj(1);

接下来, MyObj是模板类,因此在调用MyObj<int>* s1 = new MyObj<int>(1);时必须指定TMyObj<int>* s1 = new MyObj<int>(1);

因为s1s2现在是指针,所以sum不能将它们接受为指针,因此请尊重它们以获取值: sum(*s1, *s2);

正如@rgettman指出的那样, this是一个指针,因此必须使用->而不是.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM