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