条件改变时在while循环内创建一个新结构

时间:2016-06-01 18:20:07

标签: c++

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

我想在area更改时创建一个新的tokens[0]对象,但我不知道该怎么做。

此语句area(tokens[0]);会引发以下错误:

  

调用类类型的对象而不使用任何转换函数或   operator()适用于函数指针的类型

如何在需要时创建新结构?

我是C#开发人员,我无法弄清楚如何在C ++中完成它。

2 个答案:

答案 0 :(得分:4)

ConstellationArea(std::string cons)是构造函数,必须在对象初始化期间调用。

因为您正在初始化对象,所以ConstellationArea area("foo")合法是合法的。

area("foo")不是initialization,实际上它是对象operator()的调用。在这种情况下,编译器正在寻找未定义的ConstellationArea::operator()(std::string str)

您必须初始化另一个对象并将其分配给变量,例如

area = ConstellationArea(tokens[0])

这将创建另一个对象,然后通过ConstellationArea& ConstellationArea::operator=(const ConstellationArea& other) copy assignment operator为其分配值,默认情况下会提供该值。

答案 1 :(得分:1)

重新分配值?

area = ConstellationArea(tokens[0]);