代码之家  ›  专栏  ›  技术社区  ›  Bach

错误C2440:“=”:无法从“std::string[]”转换为“std::string[]”

c++
  •  3
  • Bach  · 技术社区  · 16 年前

    现在这个代码怎么了!

    页眉:

    #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 class choices[]属性。

    谢谢

    2 回复  |  直到 16 年前
        1
  •  7
  •   GManNickG    16 年前

    无法分配数组,而且数组也没有大小。你可能只是想要一个 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
    }
    
        2
  •  0
  •   Oak    16 年前

    不能将数组定义为 string _choices[] ,它定义了一个大小未知的数组,这是非法的。

    如果你把它改成 string * _choices 它将工作得很好(尽管要知道它只会复制指向数组的指针,而不是全部克隆)。

    还有,你不想 _choices 要成为类的字段,而不是全局字段?