Я только что пришел из мира Java и Python в мир 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; }
};
В конечном счете, я хочу написать весь clusterPoint
в clusterPointArray
в файл. Однако теперь я просто тестирую его с помощью первого 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)
значение из const float GetCoordinate(int nth)
?
попытайтесь изменить это
outFile << ("%f", (*it).GetCoordinate(0)); // fails
к этому:
outFile << (*it).GetCoordinate(0); // OK
Поскольку ("%f", (*it).GetCoordinate(0))
ничего не представляет, только перечисления выражений, разделенных ,
. Я не думаю, что он не будет оцениваться в пару объектов, как в java.
Edit: ("%f", (*it).GetCoordinate(0))
фактически оценивает последний элемент, который является (*it).GetCoordinate(0)
(комментарий PlasmaHH), поэтому он все равно должен что-то печатать. Однако, если ничего не напечатано, коллекция clusterEntry->clusterPointArray
может быть пуста и код внутри цикла for может не выполняться никогда.
Надеюсь, это поможет, Разван.
outFile << it->GetCoordinate(0);
std::cout << (1,2,3)
выведет3