class M{
string s[5];
M(){
s = ["abc","abc","abc","abc","abc"]; // error, how i solve it?
}
};
I want to declare a array as a private variable, then assign a value to it.
Either you can use the mem-initializer list. For example
class M
{
string s[5];
pyblic:
M() : s{ "abc", "abc", "abc", "abc", "abc" }
{
}
};
Or instead of the array you could use standard class std::array. For example
#include <array>
class M
{
std::<string, 5> s;
pyblic:
M()
{
s = { "abc", "abc", "abc", "abc", "abc" };
}
};
Arrays are not assignable. But you can use the constructor initialization list:
M() : s{"abc","abc","abc","abc","abc"}
{
}
You can also initialize the member at the point of declaration:
class M{
string s[5]= {"abc","abc","abc","abc","abc"};
M(){}
};
Both of these require C++11 compiler.
Alternatively, you can modify the array to contain the values you want. For example,
#include <algorithm> // for std::fill
M()
{
std::fill(s, s+5, "abc");
}
Use a vector instead:
std::vector<string> s;
s = {"abc","abc","abc","abc","abc"};
#include <vector> #include <stdio.h> using namespace std; class M { vector<string> s; public: M(){ s = {"abc", "abc", "abc", "abc", "abc"}; } }; int main(){ return 0; }I use vs2010 to compile it ,but can't be successfully compiled.