Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error C2440: '=' : cannot convert from 'std::string []' to 'std::string []'

Tags:

c++

now what is wrong with this code!

Header:

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

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

};

Implementation:

#include "Menu.h"

string _choices[];

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

Menu::~Menu(void)
{
}

compiler is complaining:

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

there is no conversion! so what is it on about?

please help, just need to pass a bloody array of strings and set it to Menu class _choices[] attribute.

thanks

like image 370
Bach Avatar asked Aug 23 '26 23:08

Bach


1 Answers

Array's cannot be assigned, and your arrays have no sizes anyway. You probably just want a std::vector: std::vector<std::string>. This is a dynamic array of strings, and can be assigned just fine.

// 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
}
like image 84
GManNickG Avatar answered Aug 26 '26 12:08

GManNickG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!