當我嘗試使用一種方法返回一個私有變量時,它似乎從構造對象以來的值發生了變化。這是我的代碼和輸出。C++:返回一個類變量
的main.cpp
#include <iostream>
#include "coordinate.h"
using namespace std;
int main()
{
Coordinate c(1, 1);
cout << c.getX() << endl;
}
coordinate.cpp
#include "coordinate.h"
#include <iostream>
using namespace std;
Coordinate::Coordinate(int x, int y)
{
x = x;
y = y;
cout << x << endl;
}
coordinate.h
#ifndef COORDINATE_H
#define COORDINATE_H
class Coordinate
{
private:
int x;
int y;
public:
Coordinate(int x, int y);
int getX() { return x; }
int getY() { return y; }
};
#endif
請勿張貼文字的屏幕截圖。 –