【发布时间】:2012-12-14 17:24:29
【问题描述】:
这令人费解。我需要在我的程序中使用一个函数 CCountry::getName()。奇怪的是,在测试它是否完全有效时,它在一个地方有效,但在两行以下不起作用,我不知道为什么。比如……
while(line != "---" && line != "------")
{
CCountry *tempCountry = new CCountry(line);
cout << tempCountry->getName() << flush;
(*tempContinent).addCountry(*tempCountry);
getline(filestr, line);
}
有效。它按顺序列出了所有国家/地区名称。不过……
while(line != "---" && line != "------")
{
CCountry *tempCountry = new CCountry(line);
(*tempContinent).addCountry(*tempCountry);
getline(filestr, line);
cout << tempCountry->getName() << flush;
}
不起作用。它甚至无法打印一个国家/地区名称,而是在调用 getName() 的行中抛出一个段错误。
这里有两个函数 getName() 和 addCountry() 供进一步参考
string CCountry::getName()
{
return *name;
}
和
void CContinent::addCountry(CCountry country)
{
(*countries).push_back(country);
}
根据请求,这里是 CCountry 构造函数:
CCountry::CCountry(string in_name)
{
name = new string;
*name = in_name;
player = new int;
*player = -1;
units = new int;
*units = 0;
neighbors = new list<CCountry>;
}
【问题讨论】:
-
如果您用您所询问的语言标记问题通常会有所帮助,以避免人们猜测。
-
那么下面两行包含什么?
-
对不起,新来的。从现在开始我会这样做。
-
告诉我们
CCountry的构造函数,以及局部变量line的类型。 -
您知道
->运算符吗?你可以做tempContinent->addCountry(*tempCountry)