簡體   English   中英

MSVC ++編譯器錯誤C2143

[英]MSVC++ compiler error C2143

以下代碼摘錄是一個秘密的MSVC ++編譯器錯誤的原因:

template<class T> class Vec : public vector<T>{
  public:
    Vec() : vector<T>(){}
    Vec(int s) : vector<T>(s){}

    T& operator[](int i){return at(i);  }
    const T& operator[](int i)const{ return at(i);}
};

...

錯誤:

test.cpp(5) : error C2143: syntax error : missing ',' before '<'
  test.cpp(12) : see reference to class template instantiation 'Vec<T>' being compiled

我該如何解決?

- -編輯 - -

一些背景:

我正在嘗試編譯本質上是從C ++編程語言復制和粘貼的代碼。 我什至還沒有完全理解這段代碼。 但是,目的是實現一種向量類型,當某些代碼嘗試訪問向量范圍之外的項目而不是僅返回不正確的值時,該向量類型將引發異常。

嘗試

template<class T> class Vec : public vector<T>{
  public:
    Vec() : vector(){} // no <T>
    Vec(int s) : vector(s){} // same

    T& operator[](int i){return at(i);  }
    const T& operator[](int i)const{ return at(i);}
};

模板類的構造函數的名稱中不包括模板簽名。

順帶一提,您的第二個構造函數實際上應該是

Vec(typename vector<T>::size_type s) : vector(s){} // not necessarily int

最后,您真的不應該從向量派生,因為它具有非虛擬的析構函數。 不要試圖通過指向矢量的指針刪除Vec。

為什么要嘗試從向量繼承? 這會給您帶來很多問題。 至少其中的一個問題是向量沒有虛擬析構函數。 刪除對您的類的多態引用時,這將導致調用錯誤的析構函數,這將導致內存泄漏或一般的不良行為。

例如,以下代碼將不會調用〜Vec(),而是會調用〜vector()。

vector<int> *pVec = new Vec<int>();
delete pVec;  // Calls ~vector<T>();

您看到的實際編譯錯誤是因為您正在對基本構造函數調用使用模板語法。 只需刪除它,它應該編譯

Vec() : vector() {}

MSDN:編譯器錯誤C2143(C ++)

An unqualified call is made to a type in the Standard C++ Library:
// C2143g.cpp
// compile with: /EHsc /c
#include <vector>
static vector<char> bad;   // C2143
static std::vector<char> good;   // OK

這只是咬我。 您只需修復對vector<T>引用,將其替換為std::vector<T>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM