C ++如何声明和初始化类中的向量

时间:2017-04-07 09:09:56

标签: c++ class vector member

我想使用成员函数“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”

并发出警告:

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

1 个答案:

答案 0 :(得分:0)

你有很多问题:

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

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

  4. 这是可以工作并显示您想要的代码:

    #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示例