简体   繁体   中英

How to initialize an array in a class constructor?

Working in Xcode on Mac OS X Leopard in C++:

I have the following code:

class Foo{

private:
    string bars[];

public:
    Foo(string initial_bars[]){
        bars = initial_bars;
    }
}

It does not compile and throws the following error:

error: incompatible types in assignment of 'std::string*' to 'std::string [0u]'

I notice that removing the line bars = initial_bars; solves the problem. It seems like I am not doing the assignment correctly. How could I go about fixing this problem?

EDIT:

The variable bars is an array of strings. In the main function I initialize it like this:

string bars[] = {"bar1", "bar2", "bar3"};

But it can contain an arbitrary number of members.

Arrays behave like const pointers, you can't assign pointers to them. You also can't directly assign arrays to each other.

You either

  • use a pointer member variable
  • have a fixed size of bar s you get and initialize your member array with its contents
  • just use a reference to a std container like std::vector

It is possible to "value-initialize" array members as follows:

class A {
public:
  A () 
  : m_array ()       // Initializes all members to '0' in this case
  {
  }

private:
  int m_array[10];
};

For POD types this is important as if you don't list 'm_array' in the member initialization list then the array elements will have indeterminate values.

In general it's better to initialize members in the member-initialization-list, otherwise the members will be initialized twice:

A (std::vector<int> const & v)
// : m_v ()   // 'm_v' is implicitly initialized here
{
  m_v = v;    // 'm_v' now assigned to again
}

More efficiently written as:

A (std::vector<int> const & v)
: m_v (v)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM