在类函数中初始化字符串数组

时间:2014-12-07 03:47:19

标签: c++ string initialization

我尝试在类中初始化一个字符串数组,如下所示:

class Haab{
    string str[];
    Haab(){
        str[] = {"abc", "abd", "abe"};
    }
};

但是Devc ++ 5.6.1报告了一个警告:

[Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default]

这种在类中初始化数组的方式是非法的吗?如果是这样,如何正确初始化阵列?谢谢。

1 个答案:

答案 0 :(得分:2)

给定的代码,

class Haab{
    string str[];
    Haab(){
        str[] = {"abc", "abd", "abe"};
    }
};

在许多方面无效:

  • string str[];声明一个未知大小的成员数组。不能这样做。

  • str[] = {"abc", "abd", "abe"};中,表达式str[]使用[]索引运算符而未指定索引。

  • 如果进行了解析,则=将表示单个字符串的分配。

这是一种C ++ 03做事的方式:

#include <string>
#include <vector>

namespace qwe {
    using std::string;
    using std::vector;

    class Haab
    {
    private:
        vector<string> str_;

    public:
        Haab()
        {
            static char const* const data[] = {"abc", "abd", "abe"};

            for( int i = 0; i < 3; ++i )
            {
                str_.push_back( data[i] );
            }
        }
    };
}  // namespace qwe

还有其他C ++ 03方法,所有方法都很难看(如上所述)。

在C ++ 11及更高版本中,它可以用更优雅的方式完成。简单的表示法;

#include <string>
#include <vector>

namespace qwe {
    using std::string;
    using std::vector;

    class Haab
    {
    private:
        vector<string> str_;

    public:
        Haab()
            : str_{ "abc", "abd", "abe"}
        {}
    };
}  // namespace qwe

但是仍然无法使用Visual C ++ 13.0进行编译(它使用MinGW g ++ 4.9.1进行编译)。

相关问题