Bre*_*ing 3 c++ variables class
当我尝试使用一个方法返回一个私有变量时,似乎值从构造对象开始变化.这是我的代码和输出.
main.cpp中
#include <iostream>
#include "coordinate.h"
using namespace std;
int main()
{
Coordinate c(1, 1);
cout << c.getX() << endl;
}
Run Code Online (Sandbox Code Playgroud)
coordinate.cpp
#include "coordinate.h"
#include <iostream>
using namespace std;
Coordinate::Coordinate(int x, int y)
{
x = x;
y = y;
cout << x << endl;
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

您的构造函数正在分配其参数而不是对象的私有字段.使用初始化列表,或使用明确限定赋值目标this,或选择不同的参数名称:
Coordinate::Coordinate(int x, int y) : x(x), y(y) {
cout << x << endl;
}
Run Code Online (Sandbox Code Playgroud)
要么
Coordinate::Coordinate(int x, int y) {
this->x = x;
this->y = y;
cout << x << endl;
}
Run Code Online (Sandbox Code Playgroud)
要么
Coordinate::Coordinate(int xVal, int yVal) {
x = xVal;
y = yVal;
cout << x << endl;
}
Run Code Online (Sandbox Code Playgroud)