为什么我的mutator功能没有设置?还是我的构造函数?

p.c*_*ves 2 c++ getter-setter

我正在尝试制作一个相当基本的程序但是我得到了一些非常不一致的输出.特别是setter似乎没有设置值,虽然当我以不应该改变输出的方式混淆参数变量时,我有时会得到工作结果.

这是我的代码:

point.cpp

public:

point()
{
    x = 0;
    y = 0;
}
point(double x, double y)
{
    x = x;
    y = y;
}
void set_x(double x)
{
    x = x;
}
void set_y(double y)
{
    y = y;
}
double get_x() const
{
    return x;
}
double get_y() const
{
    return y;
}
private:
double x;
double y;
};
Run Code Online (Sandbox Code Playgroud)

主要

point pointA;
double x,y;

cout << "Enter x value for point A: " << endl;
cin >> x;
pointA.set_x(x);
cout << "Enter y value for point A: " << endl;
cin >> y;
pointA.set_y(y);

point pointB(x,y);

cout << "X value for point A is: " << pointA.get_x() << endl;
cout << "Y value for point A is: " << pointA.get_y() << endl;
cout << "X value for point B is: " << pointB.get_x() << endl;
cout << "Y value for point B is: " << pointB.get_y() << endl;
Run Code Online (Sandbox Code Playgroud)

输出:

X value for point A is: 10
Y value for point A is: 10
X value for point B is: 3.18463e-314
Y value for point B is: 2.12199e-314
Run Code Online (Sandbox Code Playgroud)

我真的很困惑这一切,因为基本上相同的功能在其他类似的基本程序中工作.如果有人能够指出我正在制造什么明显的错误将非常感激.

Sto*_*ica 5

让我们检查一个构造函数,尽管问题在各处都是一样的

point(double x, double y)
{
    x = x;
    y = y;
}
Run Code Online (Sandbox Code Playgroud)

x指的是参数.所以你要将参数分配给自己.两种半解决方案是可能的:

  1. 为成员和参数使用不同的名称.
  2. this,明确地命名成员,即this->x = x;.
  3. 仅适用于c'tor.使用成员初始化列表point(double x, double y) : x(x), y(y) {}.这里有关于x初始化器内部和外部引用的内容的特殊规则.我建议您使用成员初始化列表,即使您采用以前的解决方案之一.这是更惯用的C++.

  • @ p.chives - 您确定在进行这些更改后重建了可执行文件吗?我是一个,当名称不同时,无法重现您的问题.此外,如果你打算在[so]上做出贡献,你应该知道以一种完全使现有答案无效的方式改变答案就是这里的礼节很差. (2认同)