[英]Vector in class (does not have a class type)
我在課堂上遇到一些麻煩。
#include <vector>
using namespace std;
class sth {
vector<int> tab();
public:
void add(int i);
};
void sth::add(int i){
tab.push_back(i);
}
int main() {
sth a;
a.add(10);
return 0;
}
那個簡單的代碼導致11 5 [Error] '((sth*)this)->sth::tab' does not have class type
什么想法嗎?
以下實際上是一個函數聲明:
vector<int> tab();
如果要聲明std::vector
,則應為:
vector<int> tab;
那個簡單的代碼導致
11 5 [Error] '((sth*)this)->sth::tab' does not have class type
有什么想法嗎?
您使用的是一個類成員函數聲明:
vector<int> tab();
正如我從add()
方法實現中看到的那樣,您想聲明(並初始化?)一個類成員變量 。 為此,聲明語法如下所示:
vector<int> tab;
要初始化類成員變量(即使使用其默認構造函數),也必須使用構造函數方法成員初始化列表進行定義
sth::sth() : tab() {}
對於當前的c ++標准,您還可以使用以下形式之一的直接初始化
vector<int> tab{};
vector<int> tab{1,2,3,4,5};
vector<int> tab = vector<int>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.