在类中初始化向量
Initializing vector in class
这段代码在类外运行良好 -
const char* list[] = {"Author: ", "Label: ", "Price: ", "Date: "};
vector<string> vlist(list, list+4);
但是当我把它放到类中时,它的行为就像一个函数 - 编译器给我错误"列表"不是一种类型,错误:预期的","或"..."。在"+"令牌等之前??
常见模式如下:
class MyClass {
public:
template<class It>
MyClass(It beg, It end) : vec(beg,end) { }
private:
std::vector<std::string> vec;
};
int main() {
std::string s[] = { "abc", "bcd" };
MyClass c(s, s+2);
};
您收到错误,因为类定义无法调用函数,只能声明它们。您可以使用类构造函数中的初始值设定项列表来解决此问题:
const char* list[] = { "Author: ", "Label: ", "Price: ", "Date: " };
class c
{
vector<string> vlist;
c() : vlist(list, list + 4) {}
}
数组大小不能在类内初始值设定项中自动推导。相反,您需要指定大小:
const char* list[4] = {"Author: ", "Label: ", "Price: ", "Date: "};
您的vlist
成员可以从临时成员初始化:
vector<string> vlist = vector<string>(list, list + 4);
但这可能效率低下。最好在构造函数中初始化它,以避免临时性。
但是,您确定需要纯list
阵列吗?因为如果没有,这样做要容易得多:
vector<string> list = {"Author: ", "Label: ", "Price: ", "Date: "};
此外,您需要确保已在编译器中启用了 C++11 模式。使用GCC或Clang,这将是-std=c++11
或-std=g++11
(对于GNU扩展)编译器标志。
如果您使用的是 C++11,则可以通过初始值设定项列表直接初始化向量:
vector<string> vlist {"Author: ", "Label: ", "Price: ", "Date: "};
如果没有,您必须在构造函数中执行此操作,最有可能通过push_back
Class::Class() {
vlist.push_back("Author :");
vlist.push_back("Label :");
vlist.push_back("Price :");
vlist.push_back("Date :");
}
无论如何,如果最终要使用vector
,创建中间 C 样式表是没有意义的。
相关文章:
- 为什么我在向量初始化时收到此错误?
- 使用向量初始化参数化构造函数的对象数组
- C++向量初始化遗传算法的代理向量
- shared_ptr类的向量的向量初始化问题
- 如何实现使用 gcc-4.4 编译的大向量初始化?
- 使用向量初始化C++中的链表
- C++ 中的向量初始化
- 如何使用嵌套初始化构造函数中的一维向量初始化矩阵
- std::另一个函数中的向量初始化
- 理解向量初始化时出现问题
- 静态常量 std::<char>没有堆的向量初始化?
- 向量初始化在 C++ 类中失败
- 具有从特定范围的随机数初始化特征矩阵或向量初始化特征矩阵或向量的有效方法
- 关于向量初始化的一些问题
- 了解C 中的向量初始化
- 设置::使用数字中的引号进行向量初始化
- VS2010中的向量初始化
- C++:构造函数中的向量初始化
- 如何从向量初始化数组?(如何将指针强制转换为数组?)
- 给我一个向量初始化的提示或(答案)