scr*_*out 1 c++ parameters constructor initialization
我有一个基类,Point其中包含3个要派生为Body属性的变量。我想初始化一个点,并用它来初始化主体对象。这是我到目前为止的内容:
#include <iostream>
using namespace std;
class Point {
public:
double x, y, z;
// default constructor
Point(): x(0), y(0), z(0){
};
// intialization constructor
Point(double x, double y, double z){
x = x;
y = y;
z = z;
}
// copy constructor
Point(const Point &point){
x = point.x;
y = point.y;
z = point.z;
}
void print_point(){
cout << "x = "<< x << " y = " << y << " z = " << z << endl;
}
};
class Body: public Point{
public:
double mass;
// default constructor
Body(): Point(0, 0, 0), mass(0){
};
// intialization constructor
Body(const Point& point, double mass): Point(point.x, point.y, point.z){
mass = mass;
}
// copy constructor
Body(const Body &body): Point(body){
mass = body.mass;
}
void print_body(){
cout << "x = "<< x << " y = " << y << " z = " << z << " mass = " << mass << endl;
}
};
int main() {
Point p(1., 2., 3.);
p.print_point();
Body b(p, 65.);
b.print_body();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我编译并运行它时,我得到:
x = 0 y = 0 z = 6.95312e-310
x = 2.25081e-314 y = 0 z = 0 mass = 0
Run Code Online (Sandbox Code Playgroud)
当我期望得到:
x = 1 y = 2 z = 3
x = 1 y = 2 z = 3 mass = 65
Run Code Online (Sandbox Code Playgroud)
就像变量已由默认构造函数重置一样,我不知道是什么原因造成的。
您应该将构造函数主体中的分配从
x = x;
y = y;
z = z;
Run Code Online (Sandbox Code Playgroud)
至
this->x = x;
this->y = y;
this->z = z;
Run Code Online (Sandbox Code Playgroud)
在构造函数的主体内部,参数的名称隐藏了数据成员的名称。例如,x = x;仅将参数分配x给自身,而不分配数据成员x。该类Body有相同的问题。
更好的方法是使用成员初始值设定项list初始化数据成员(顺便说一句,它没有这样的名称隐藏问题)。例如
Point(double x, double y, double z) : x(x), y(y), z(z) {}
Run Code Online (Sandbox Code Playgroud)