【问题标题】:C++ How to declare and initialize a vector inside a classC ++如何在类中声明和初始化向量
【发布时间】:2017-04-07 09:09:56
【问题描述】:

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

在类体内向量“颜色”的声明和初始化时

还有一个警告:

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

【问题讨论】:

  • #include &lt;vector&gt;了吗?此外,您需要去掉头文件中colors= 之间的分号。
  • 还有一个支持 c++11 的编译器。
  • 只需在编译器的标志中启用 C++14 或 C++11。但是,您仍然会遇到std::cout &lt;&lt; colors 的问题,因为std::vector 没有&lt;&lt; 的重载。
  • 除了 hlt 所说的之外,您正在使用 cout 打印字符串向量,但 cout 不知道该怎么做。必须做什么(循环遍历向量的所有值并打印每个值)对您来说可能很明显,但编译器并不知道。在 Color::print() 函数中添加显式 for 循环!例如,它们是否应该用空格、逗号、逗号和空格、换行符分隔?你必须决定它,没有标准的方法!所以这样做的方法甚至不是明显......
  • 请麻烦制作一个minimal reproducible example。应该不难。你可能错过了 std::vector 或 std::string 的声明 - 你真的需要在等号之前去掉那个分号。

标签: c++ class vector member


【解决方案1】:

你有很多问题:

  1. 写一次std::然后离开。
  2. 语法错误:std::vector&lt;std::string&gt; 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 示例

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-10
    • 2017-01-11
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    相关资源
    最近更新 更多