无法从C++;? 我刚刚从java和python世界来到C++世界,在试图从一个公共的代码> const 函数中获取值时遇到了一个问题。

无法从C++;? 我刚刚从java和python世界来到C++世界,在试图从一个公共的代码> const 函数中获取值时遇到了一个问题。,c++,C++,我的课程如下: 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:

我的课程如下:

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
s写入文件中。然而,现在我只是用第一个
集群点
(因此,
GetCoordinate(0)
)来测试它

流出管的
;
open(“C:\\data\\test.txt”,std::ofstream::out | std::ofstream::app);
对于(std::vector::iterator it=clusterEntry->clusterPointArray.begin();it!=clusterEntry->clusterPointArray.end();+it)
{
outFile尝试更改此选项

outFile << ("%f", (*it).GetCoordinate(0)); // fails
outFile
outFile获取坐标(0);

只需使用
outFile GetCoordinate(0);
。我还建议使用
std::vector
而不是数组,然后使用
m_坐标,在
CMDPoint::GetCoordinate
中添加边界检查如果你是C++的新手,否则你可能会遇到StError。@ McCelaSeNe,不,还是一样。
实际上有一个值。您不需要进行错误检查。您不需要返回
const int
const float
。这是多余的。您不需要强制用户将其作为常量处理。我认为clusterEntry->clusterPointArray没有元素。如果代码实际上进入for循环,您可以使用调试器进行检查。它将实际上要计算到最后一个,就像std::cout Plasmah 4你说得对,我想知道这是怎么编译的,我从来没有用过它。@perfectionm1ng那么你的m_坐标没有指向有效的数组。
outFile << ("%f", (*it).GetCoordinate(0)); // fails
outFile << (*it).GetCoordinate(0); // OK
outFile << it->GetCoordinate(0);