2010-06-13 159 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

相关问题