Reputation: 2694
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
Upvotes: 3
Views: 2822
Reputation: 26898
You can't define the array as string _choices[]
, that defines an array with unknown size, which is illegal.
If you change it to string * _choices
it will work just fine (though be aware it will only copy a pointer to the array, and not clone it all).
Also, don't you want _choices
to be a field of the class, instead of a global?
Upvotes: 0
Reputation: 504333
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
}
Upvotes: 7