当条件更改时,在 while 循环内创建新结构
Create a new struct inside a while loop when condition changes
我正在使用Visual Studio 2015开发一个C++静态库。
我有以下结构:
struct ConstellationArea
{
// Constellation's abbrevation.
std::string abbrevation;
// Area's vertices.
std::vector<std::string> coordinate;
ConstellationArea(std::string cons) : abbrevation(cons)
{}
};
我在一段时间内使用它(请注意,该方法尚未结束):
vector<ConstellationArea>ConstellationsArea::LoadFile(string filePath)
{
ifstream constellationsFile;
vector<ConstellationArea> areas;
string line;
ConstellationArea area("");
string currentConstellation;
// Check if path is null or empty.
if (!IsNullOrWhiteSpace(filePath))
{
constellationsFile.open(filePath.c_str(), fstream::in);
// Check if I can open it...
if (constellationsFile.good())
{
// Read file line by line.
while (getline(constellationsFile, line))
{
vector<string> tokens = split(line, '|');
if ((currentConstellation.empty()) ||
(currentConstellation != tokens[0]))
{
currentConstellation = tokens[0];
areas.push_back(area);
area(tokens[0]);
}
}
}
}
return areas;
}
我想在tokens[0]
更改时创建一个新的area
对象,但我不知道该怎么做。
此语句area(tokens[0]);
引发以下错误:
调用没有任何转换函数的类类型的对象或 运算符 () 适用于函数指针的类型
如何在需要时创建新结构?
我是一名 C# 开发人员,我不知道如何在C++中做到这一点。
ConstellationArea(std::string cons)
是一个构造函数,必须在对象初始化期间调用。
因此,使用ConstellationArea area("foo")
是合法的,因为您正在初始化对象。
但area("foo")
不是初始化,实际上是对对象operator()
的调用。在这种情况下,编译器正在寻找未定义的ConstellationArea::operator()(std::string str)
。
您必须初始化另一个对象并将其分配给变量,例如
area = ConstellationArea(tokens[0])
这将创建另一个对象,然后通过ConstellationArea& ConstellationArea::operator=(const ConstellationArea& other)
复制赋值运算符为其赋值,默认情况下提供该值。
重新分配值?
area = ConstellationArea(tokens[0]);
相关文章:
- C++:添加新结构时,结构指针向量中的所有元素都会更新
- 使用新运算符C++创建多维数组的简单方法
- CLang:在 std::thread 中运行函数会导致结构创建BAD_ACCESS
- C++为API中定义的结构创建超类
- 是否需要删除函数中未使用的新结构?
- 有没有办法初始化不涉及编写构造函数的新结构变量?
- C++ 使用数组结构创建平衡的二叉搜索树
- C 矢量元素擦除与新向量创建
- 使用匿名联合为结构创建空构造函数
- cpp 中是否存在一种数据结构,可以轻松地提供一种基于已存在的实例构建新结构的方法
- 为什么可以使用指针创建新结构,但不能以相同的方式创建双精度?
- 对新结构的Oploading Operator()
- C++ 为什么我制作新结构并得到错误?(双链表通函)
- 元编程:动态声明一个新结构
- 如何使用安置新操作员创建对象数组
- 当条件更改时,在 while 循环内创建新结构
- 多次创建新结构
- 如何在创建新结构体时给成员指针赋NULL值
- 在C++中为树创建新结构
- 动态创建新结构