现在这段代码有什么问题!
标题:
#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
没有转换!那么它是关于什么的?
请帮忙,只需要传递一个血腥的字符串数组并将其设置为菜单类 _choices[] 属性。
谢谢
最佳答案
无法分配数组,并且您的数组无论如何都没有大小。你可能只想要一个 std::vector
: std::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
}
关于c++ - 错误 C2440 : '=' : cannot convert from 'std::string []' to 'std::string []' ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3031336/