2014-01-20 33 views
0

我一直在嘗試通過創建基於文本的遊戲來學習C++。在這個遊戲中,我創建了一個MapHandler,它有一個網格(多維數組,5x5,int)。我希望能夠在被調用時將這個類傳遞給一個網格,但我似乎無法做到這一點。C++:如何在類中啓動數組?

我的問題是:我如何設置一個值 - 從外部 - 爲一個類中的數組?

我已經寫了一些代碼,複製我的錯誤:

// ConsoleApplication2.cpp : Defines the entry point for the console application. 
// 

#include "stdafx.h" 
#include <iostream> 
#include <string> 

using namespace std; 

class Person { 
    public: 
     int age; 
     string characteristics[5]; 
     Person(); 
}; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    string traits[5] = {'Stubborn','Ambitious','Smart','Emotional','Extrovert'}; 
    Person Bob; 

    Bob.age = 18; 
    Bob.characteristics = traits; 

    system("Pause"); 
    return 0; 
} 
+2

for(int i = 0; i < 5; ++i) Bob.characteristics[i] = traits[i]; 

,甚至更好「我一直在努力學習C++創建一個基於文本的遊戲。」 - 嘗試閱讀介紹性書籍。 –

+1

使用['std :: array'](http://en.cppreference.com/w/cpp/container/array) – Borgleader

+2

字符串應該用雙引號引用而不是單引號:''Stubborn'' – billz

回答

1

問題是您無法複製原始數組(即int a[5], b[5]; b=a;)。你將不得不通過元素複製這些元素:

#include <algorithm> 


// ... 

std::copy(traits, traits+5, Bob.characteristics); 
4

在C++中,普通的數組是不是一流的,即它們不能被複制。您可以改用std::array來獲益。