2012-12-06 82 views
0

我保證我已經找遍了很多年以找到解決方案,但無濟於事,但是我沒有經歷過C++,所以也許我只是不知道要搜索什麼。在構造函數中初始化矢量C++

我想最簡單的做法是首先向我展示我的錯誤代碼,以防它被識別。這有點堆,這就是爲什麼我無法弄清楚它是什麼問題。 (也就是我覺得它的東西,無論是出於我的理解,或者真的很煩人的錯誤,我做!)

g++ -Wall -pedantic -ansi -std=c++0x -g -c -o contacts.o contacts.cc 
In file included from /usr/include/c++/4.6/vector:63:0, 
      from contacts.h:5, 
      from contacts.cc:2: 
/usr/include/c++/4.6/bits/stl_construct.h: In function ‘void std::_Construct(_T1*, 
_Args&& ...) [with _T1 = person, _Args = {}]’: 
/usr/include/c++/4.6/bits/stl_uninitialized.h:481:3: instantiated from ‘static void 
std::__uninitialized_default_n_1<_TrivialValueType>::__uninit_default_n(_ForwardIterator, 
_Size) [with _ForwardIterator = person*, _Size = unsigned int, bool _TrivialValueType = 
false]’ 
/usr/include/c++/4.6/bits/stl_uninitialized.h:529:7: instantiated from ‘void 
std::__uninitialized_default_n(_ForwardIterator, _Size) [with _ForwardIterator = 
person*, _Size = unsigned int]’ 
/usr/include/c++/4.6/bits/stl_uninitialized.h:604:7: instantiated from ‘void 
std::__uninitialized_default_n_a(_ForwardIterator, _Size, std::allocator<_Tp>&) [with 
_ForwardIterator = person*, _Size = unsigned int, _Tp = person]’ 
/usr/include/c++/4.6/bits/stl_vector.h:1134:2: instantiated from ‘void 
std::vector<_Tp, _Alloc>::_M_default_initialize(std::vector<_Tp, _Alloc>::size_type) 
[with _Tp = person, _Alloc = std::allocator<person>, std::vector<_Tp, 
_Alloc>::size_type = unsigned int]’ 
/usr/include/c++/4.6/bits/stl_vector.h:239:9: instantiated from ‘std::vector<_Tp, 
_Alloc>::vector(std::vector<_Tp, _Alloc>::size_type) [with _Tp = person, _Alloc = 
std::allocator<person>, std::vector<_Tp, _Alloc>::size_type = unsigned int]’ 
contacts.cc:7:38: instantiated from here 

編輯: 道歉,我不完全理解我在做什麼,但我希望這是你要求的。

Contacts.h:

#ifndef _CONTACTS_H 
#define _CONTACTS_H 

#include <iostream> 
#include <vector> 

#include "person.h" 


class contacts{ 
    private: 
    int element; 
    int count; 
    vector<person> pv; 

    public: 
    contacts(); 
}; 
#endif 

和contacts.cc:

#include "contacts.h" 

using namespace std; 


contacts::contacts() : count(0), pv(0) {} 

如果我有起碼這麼多在我的代碼(這兩個相關的文件)依然出現謝謝 -Ewan

+0

後再現問題的最少代碼。縮小範圍。把它剪成最小的一塊。 –

+0

是的,至少把你的聯繫人類標題放在這裏。 –

+0

這個問題可能與人員課程有關;請張貼標題;你會想要爲'person'定義可訪問的默認和複製構造函數。 – Keith

回答

1

爲什麼你將0傳遞給std :: vector <>構造函數?這聽起來像是它已經從你寫的同樣的效果:

contacts::contacts() : count(0) {}

+0

*注意:我的邏輯可能有缺陷,但這裏是:* 我以爲我需要初始化我的向量以在代碼的其餘部分使用它,但我無法在構造函數之前初始化它,或者我收到了不同的代碼錯誤。 (至少我認爲它需要初始化??) – Displonker

+0

@Displonker:'vector'有一個默認構造函數......它將被正確地構造而不包含元素。對於所有的標準容器(包括'std :: string'),典型的智能指針類都是如此,但對於像'int','char','double'和'[]'這樣的數組類型的類型不是這樣。 –

+0

@Displonker在您的構造函數體開始執行之前,您的向量將自動初始化(通過它的默認構造函數)。它將是空的。如果你想實際填充矢量,你可以在你的構造函數中做到這一點,如果你願意。 – wjl