如何在类构造函数中初始化数组?

Yuv*_*rmi 4 c++ oop

使用C++ 在Mac OS X Leopard上使用Xcode:

我有以下代码:

class Foo{

private:
    string bars[];

public:
    Foo(string initial_bars[]){
        bars = initial_bars;
    }
}
Run Code Online (Sandbox Code Playgroud)

它不编译并抛出以下错误:

error: incompatible types in assignment of 'std::string*' to 'std::string [0u]'
Run Code Online (Sandbox Code Playgroud)

我注意到删除线bars = initial_bars;解决了问题.好像我没有正确地完成任务.我怎么能解决这个问题呢?

编辑:

变量条是一个字符串数组.在main函数中,我将它初始化为:

string bars[] = {"bar1", "bar2", "bar3"};
Run Code Online (Sandbox Code Playgroud)

但它可以包含任意数量的成员.

Geo*_*che 8

数组的行为类似于const指针,您无法为它们指定指针.您也无法直接为彼此分配数组.

你要么

  • 使用指针成员变量
  • bar你得到一个固定大小的s,并用你的内容初始化你的成员数组
  • 只需使用对std容器的引用即可std::vector