我想使用成员函数“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.
答案 0 :(得分:0)
你有很多问题:
std::
,然后离开。语法错误:std::vector<std::string> colors; = {"red", "green", "blue"};
^
您必须遍历向量才能获取所有项目。
这是可以工作并显示您想要的代码:
#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示例