当条件更改时,在 while 循环内创建新结构

Create a new struct inside a while loop when condition changes

本文关键字:新结构 创建 结构 循环 while 条件      更新时间:2023-10-16

我正在使用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]);