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