2017-04-22 30 views
0

你好,我知道,要聲明一個std::vector我必須做這樣的如何在hpp中聲明一個向量?

std::vector<double> a(0); 

但在我的文件,這是行不通的。這裏是我的代碼:

main.cpp中:

#include "test.hpp" 

int main() 
{ 
    Test test; 
    return EXIT_SUCCESS; 
} 

test.hpp:

#ifndef DEF_TEST 
#define DEF_TEST 

#include <iostream> 
#include <vector> 

class Test 
{ 
public: 
    Test(); 
private: 
    std::vector<double> a(0); 
}; 

#endif 

,這是TEST.CPP:

#include "test.hpp" 

Test::Test() 
{ 
    a.push_back(2.3); 
    std::cout << a[0] << std::endl; 
} 

,編譯器告訴我:

In file included from main.cpp:1:0: 
test.hpp:11:23: error: expected identifier before numeric constant 
std::vector<double> a(0); 
        ^
test.hpp:11:23: error: expected ‘,’ or ‘...’ before numeric constant 
In file included from test.cpp:1:0: 
test.hpp:11:23: error: expected identifier before numeric constant 
std::vector<double> a(0); 
        ^
test.hpp:11:23: error: expected ‘,’ or ‘...’ before numeric constant 
test.cpp: In constructor ‘Test::Test()’: 
test.cpp:5:1: error: ‘((Test*)this)->Test::a’ does not have class type 
a.push_back(2.3); 
^ 
test.cpp:6:17: error: invalid types ‘<unresolved overloaded function type>[int]’ for array subscript 
std::cout << a[0] << std::endl; 

謝謝你的幫助!

回答

3

您可以使用語法初始化varible寫的方法:

std::vector<double> a(0); 

但是你不能在類成員的類初始化中使用它。要初始化類的成員,可以使用下面的語法:

std::vector<double> a = {}; 
1

你必須執行以下操作來初始化矢量作爲類成員:

class Test{ 
public: 
    Test(); 
private: 
    std::vector<double> a = std::vector<double>(0); 
}; 

FYI,此代碼大小的矢量0,這是多餘的。您可以簡單地編寫std::vector<double> a,其大小將爲0開頭。在其他情況下,如果你想在矢量是尺寸n的,那麼你用我用的n不是0

2

的std ::矢量成員將被默認初始化當創建類的實例初始化得到。

如果你想顯式調用初始化向量,你可以這樣來做你Test.cpp的文件:

Test::Test(): 
a(0) { 
    //... 
} 

詩篇。這樣做的一個優點是你也可以初始化屬於你類的常量。

0

您可以將建築工後,使用此的初始化器列表

Test::Test() : a(0) 
{ 
    ... 
} 

您需要從.HPP文件(0)刪除。

4

在我看來,你不能爲類的成員聲明使用構造函數;要在類中爲矢量使用構造函數,必須在類的構造函數中指定它,例如

class Test { 
private: 
    vector<double> a; 
public: 
    Test() : a(0) {;} 
};