C++如何声明和初始化类中的向量
问题描述:
我想使用成员函数“print”打印矢量“颜色”。C++如何声明和初始化类中的向量
/* 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.
答
你有很多问题:
- 写一次
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例如
你有没有'的#include'?另外,你需要去掉头文件中'colors'和'='之间的分号。 –
hlt
和一个支持C++ 11的编译器。 –
只需在编译器的标志中启用C++ 14或C++ 11即可。但是,对于std :: cout Quentin