为什么指针神奇地变为 NULL?

  • 本文关键字:NULL 神奇 指针 c++
  • 更新时间 :
  • 英文 :


我正在执行代码,而 c++ 指针神奇地变为空。

我尝试在我的代码中添加一些打印语句来调试它。

这是我的主类中的一些代码: ...

Vector3D* netForce = new Vector3D(0, forceY, 0);
Vector3D* accel = netForce->scalarMultiply(1.0/(*mass));
Vector3D *position = new Vector3D(75,initialHeight,0);
Vector3D* velocity = new Vector3D(0,0,0);
cout << "Sending in acceleration: " << *accel << "n";
UberPhysics* uber = new UberPhysics(position, velocity, accel);
cout << "Uber acceleration: " << uber->getAcceleration();
...

以下是 UberPhysics 构造函数的完整源代码:

UberPhysics::UberPhysics(Vector3D* position, Vector3D* velocity, Vector3D* 
acceleration, Vector3D* jerk, Vector3D* hyperJerk) {
cout << "Check Acceleration: " << acceleration << endl;
this->position = position;
this->velocity = velocity;
this->acceleration = acceleration;
this->jerk = jerk;
this->hyperJerk = hyperJerk;
}

下面是标量乘法的函数实现:

Vector3D* Vector3D::scalarMultiply(double c) {
Vector3D* v = new Vector3D(this->x*c, this->y*c, this->z*c);
return v;
}

下面是运算符<<重写:

friend ostream& operator<<(ostream &os, Vector3D& v) {
os << "<" << v.getX() << ","  << v.getY() << "," << v.getZ() << ">";
return os;
}

"发送加速:"打印语句将打印向量。 因此,当我将加速度传递给 UberPhysics 时,它表明向量不为空。 当构造函数运行时,它表示加速指针为 0。 如果我将加速作为指向堆栈上局部变量的指针传递,我可以看到这是一个问题,但是 Vector3D 函数使用 new 运算符在堆上分配类。 有谁知道问题可能是什么?

仅当您的 uberphysics 类是一个派生类,该派生类从具有默认构造函数和其他初始化数据成员的非默认构造函数的基类继承了加速指针数据成员时,才会发生这种情况。如果是这种情况,当您尝试创建派生对象时,将调用基类的默认构造函数 class.to 覆盖它,在定义派生类构造函数主体的大括号之前使用成员初始值设定项运算符...

最新更新