C++ 如何在 class 中声明和初始化向量

C++ How to declare and initialize a vector inside a class

我想使用成员函数 "print" 打印出向量 "colors"。

/* Inside .h file */
class Color
{
public:
    void print();

private:
    std::vector<std::string> colors; = {"red", "green", "blue"};
};

/* Inside .cpp file */

void Color::print() 
{ 
    cout << colors << endl;
}

但我收到一条错误消息:

Implicit instantiation of undefined template.

在向量 "colors" 内部 class body

的声明和初始化处

还有一个警告:

In class initialization of non-static data member is a C++11 extension.

你有很多问题:

  1. 写一次std::然后就离开了
  2. 语法错误:std::vector<std::string> colors; = {"red", "green", "blue"};

                                                ^ 
    
  3. 您必须遍历向量才能获得所有项目。

这是可以显示您想要的内容的代码:

#include <string>
#include <iostream>
#include <vector>

/* Inside .h file */
class Color
{
public:
    void print();

private:
    std::vector<std::string> colors = {"red", "green", "blue"};
};

/* Inside .cpp file */

void Color::print() 
{ 
    for ( const auto & item : colors )
    {
        std::cout << item << std::endl;
    }
}

int main()
{
    Color myColor;

    myColor.print();
}

Live 例子