我正在尝试制作一个相当基本的程序但是我得到了一些非常不一致的输出.特别是setter似乎没有设置值,虽然当我以不应该改变输出的方式混淆参数变量时,我有时会得到工作结果.
这是我的代码:
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)
我真的很困惑这一切,因为基本上相同的功能在其他类似的基本程序中工作.如果有人能够指出我正在制造什么明显的错误将非常感激.
让我们检查一个构造函数,尽管问题在各处都是一样的
point(double x, double y)
{
x = x;
y = y;
}
Run Code Online (Sandbox Code Playgroud)
x指的是参数.所以你要将参数分配给自己.两种半解决方案是可能的:
this,明确地命名成员,即this->x = x;.point(double x, double y) : x(x), y(y) {}.这里有关于x初始化器内部和外部引用的内容的特殊规则.我建议您使用成员初始化列表,即使您采用以前的解决方案之一.这是更惯用的C++.| 归档时间: |
|
| 查看次数: |
82 次 |
| 最近记录: |