簡體   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