2010-06-13 110 views
3

現在這個代碼有什麼問題!錯誤C2440:'=':無法從'std :: string []'轉換爲'std :: string']'

頁眉:

#pragma once 
#include <string> 
using namespace std; 

class Menu 
{ 
public: 
    Menu(string []); 
    ~Menu(void); 

}; 

實現:

#include "Menu.h" 

string _choices[]; 

Menu::Menu(string items[]) 
{ 
    _choices = items; 
} 

Menu::~Menu(void) 
{ 
} 

編譯器抱怨:

error C2440: '=' : cannot convert from 'std::string []' to 'std::string []' 
There are no conversions to array types, although there are conversions to references or pointers to arrays 

沒有轉換!那麼關於什麼?

請幫忙,只需要傳遞一個血腥的字符串數組並將其設置爲Menu類_choices []屬性。

謝謝

回答

7

無法分配數組,無論如何您的數組沒有大小。您可能只需要一個std::vectorstd::vector<std::string>。這是一個動態的字符串數組,可以很好地分配。

// Menu.h 
#include <string> 
#include <vector> 

// **Never** use `using namespace` in a header, 
// and rarely in a source file. 

class Menu 
{ 
public: 
    Menu(const std::vector<std::string>& items); // pass by const-reference 

    // do not define and implement an empty 
    // destructor, let the compiler do it 
}; 

// Menu.cpp 
#include "Menu.h" 

// what's with the global? should this be a member? 
std::vector<std::string> _choices; 

Menu::Menu(const std::vector<std::string>& items) 
{ 
    _choices = items; // copies each element 
} 
+0

謝謝GMan,這當然是非常豐富和工作。 我也移動_choices成爲會員。歡呼 – Bach 2010-06-13 07:03:15

0

不能定義數組作爲string _choices[],其限定具有未知的大小,這是非法的陣列。

如果將其更改爲string * _choices它將工作得很好(但請注意,它只會將指針複製到數組中,而不會將其全部克隆)。

此外,你不想_choices是一個類的領域,而不是一個全球?

+0

命名空間範圍數組未在堆棧上分配。 – 2010-06-13 09:55:23

+0

@Johannes:我的壞 - 修復。 – Oak 2010-06-13 11:33:11

相關問題