0
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.

3 Answers 3

4

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" };
    }
};
Sign up to request clarification or add additional context in comments.

Comments

1

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");
}

2 Comments

If I use vs2010 which don't support C++11, how to accomplish it?
If the elements in the array were different from each other,eg {"a","b","c","d","e"} how to accomplish it in a simple way without c++11 supported?
0

Use a vector instead:

std::vector<string> s;
s = {"abc","abc","abc","abc","abc"};

1 Comment

#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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.