我刚从Java转到C++世界,在尝试从类的公共const函数中获取值时遇到了一个问题。
我有一堂课如下:
class CMDPoint
{
public:
CMDPoint();
CMDPoint(int nDimensions);
virtual ~CMDPoint();
private:
int m_nDimensions; // the number of dimensions of a point
float* m_coordinate; // the coordinate of a point
public:
const int GetNDimensions() const { return m_nDimensions; }
const float GetCoordinate(int nth) const { return m_coordinate[nth]; }
void SetCoordinate(int nth, float value) { m_coordinate[nth] = value; }
};最终,我希望将在clusterPointArray中的所有clusterPoint写入文件中。但是,now --我只是在用first clusterPoint (例如GetCoordinate(0))来测试它。
ofstream outFile;
outFile.open("C:\\data\\test.txt", std::ofstream::out | std::ofstream::app);
for (std::vector<CMDPoint> ::iterator it = clusterEntry->clusterPointArray.begin(); it != clusterEntry->clusterPointArray.end(); ++it)
{
outFile << ("%f", (*it).GetCoordinate(0)); // fails
outFile << " ";
}
outFile << "\n";
outFile.close();问题是我只在文件中看到了" "。没有任何坐标被写入。在从const float GetCoordinate(int nth)获取值时,我做错了什么吗?
发布于 2013-10-09 15:00:14
试着改变这个
outFile << ("%f", (*it).GetCoordinate(0)); // fails对此:
outFile << (*it).GetCoordinate(0); // OK因为("%f", (*it).GetCoordinate(0))不代表任何东西,所以只有一个由,分隔的表达式枚举。我认为,它不会像在java中那样被计算成一对对象。
编辑:("%f", (*it).GetCoordinate(0))实际上计算为最后一个元素,即(*it).GetCoordinate(0) ( PlasmaHH注释),因此它仍然应该打印一些内容。但是,如果没有打印任何内容,那么集合clusterEntry->clusterPointArray可能是空的,并且for循环中的代码可能永远不会执行。
希望这能帮上忙Razvan。
发布于 2013-10-09 15:01:45
outFile << it->GetCoordinate(0);https://stackoverflow.com/questions/19275520
复制相似问题