c++ - 当条件改变时在 while 循环中创建一个新结构

标签 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;
}

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

这条语句 area(tokens[0]); 抛出以下错误:

call an object of a class type without any conversion function or operator () suitable for the type of function pointer

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

我是一名 C# 开发人员,但我不知道如何在 C++ 中做到这一点。

最佳答案

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它是默认提供的。

关于c++ - 当条件改变时在 while 循环中创建一个新结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37576078/

相关文章:

python - GLIBC_2.14 未找到,如果我不是 root,我该怎么办

c++ - 如果 std::move 用作 && 参数的参数,它是否会调用复制运算符?

c++ - 函数 std::arg() 的范围是多少?

c++ - 递归取消引用指针

c++ - Xalan C++ : returning a node with XPath (reference to local pointer)

c++ - 用颜色代替颜色?

python - 在 C++ 和 Python 程序中使用命名管道的 IPC 挂起

c++ - 如何从函数返回 void*?

c++ - 用 cin 读取两个整数后如何忽略换行符?

c++ - 为什么调用 CDialog::OnShowWindow 会挂起我的应用程序?