2017-04-22 2 views
0

안녕하세요 나는 내가이hpp에서 벡터를 선언하는 방법은 무엇입니까?

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

처럼하지만 내 파일이 작동하지 않습니다 할 가지고 std::vector 선언 알고있다.

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

0의 작성 한 방법을 사용 클래스 멤버의 클래스 내 초기화에는이 클래스를 사용할 수 없습니다. 최강의 멤버를 초기화하려면, 다음과 같은 구문을 사용할 수 있습니다 : 클래스의 인스턴스가 생성되면

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

당신은 클래스 멤버로 벡터를 초기화하려면 다음을 수행해야합니다

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

참고로,이 코드는 중복 0에 벡터를, 크기. 당신은 간단하게 std::vector<double> a를 쓸 수 있으며 그 크기는 0입니다.

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

: 당신이 크기 n의로 벡터를 원하는 경우 다른 경우에는, 당신은 내가 당신이 구문을 사용하여 varible을 초기화 할 수 있습니다 n 대신

2

표준 : : 벡터 멤버는 기본 초기화에 의해 초기화 얻을 것이다. 명시 적으로 벡터 초기화를 호출 할 경우

당신은 당신의 Test.cpp에 파일에서이 방법을 수행 할 수 있습니다

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

시를. 이것의 장점은 클래스의 멤버 인 상수를 초기화 할 수 있다는 것입니다.

0

당신은 당신은 (0) 귀하의 .HPP 파일에서 제거해야

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

당신의 constructer 후이에 대한 initialiser 목록을 사용할 수 있습니다.

4

클래스의 멤버 선언에 생성자를 사용할 수없는 것처럼 보입니다. 클래스의 벡터에 대한 생성자를 사용하려면 클래스의 생성자에서 지정해야합니다 (예 :

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