为什么我的值没有被我的初始化(参数化)构造函数初始化?

Why aren't my values being initialized by my initialization (parameterized) constructors?

我有一个基础 class Point,其中包含 3 个变量,我希望派生为 Body 属性。我想初始化一个点并用它来初始化一个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;
}

当我编译并运行这个时,我得到:

x = 0 y = 0 z = 6.95312e-310
x = 2.25081e-314 y = 0 z = 0 mass = 0

当我期望得到:

x = 1 y = 2 z = 3
x = 1 y = 2 z = 3 mass = 65

好像变量被默认构造函数重置了,我不知道是什么原因造成的。

您应该将构造函数体内的赋值从

更改为
x = x;
y = y;
z = z;

this->x = x;
this->y = y;
this->z = z;

在构造函数体内,参数的名称隐藏数据成员的名称。例如x = x;只是将参数x赋值给自己,并没有赋值数据成员x。 class Body 有同样的问题。

更好的方法是使用 member initializer list 初始化数据成员(顺便说一句,它没有这样的 name hiding 问题)。例如

Point(double x, double y, double z) : x(x), y(y), z(z) {}