在C++中继承布尔字段 我对C++很陌生。我创建了一个名为shape.h的接口,我希望它们继承两个类:plane.cpp和sphere.cpp都有自己的.h文件。我不知道这是否相关,但我认为值得一提。 shape.h的一个字段是:bool isRound,我希望sphere.cpp构造函数将其更改为true,而plane.cpp构造函数将其更改为false。我在sphere中就是这样做的: sphere::sphere(Vector3f Center, float Radius, Vector3f Ka, Vector3f Kd, Vector3f Ks, float Shininess) : shape(Ka, Kd, Ks, Shininess){ this->ka = Ka; this->kd = Kd; this->ks = Ks; this->radius = Radius; this->center = Center; this->shininess = Shininess; this->isRound = true; }

在C++中继承布尔字段 我对C++很陌生。我创建了一个名为shape.h的接口,我希望它们继承两个类:plane.cpp和sphere.cpp都有自己的.h文件。我不知道这是否相关,但我认为值得一提。 shape.h的一个字段是:bool isRound,我希望sphere.cpp构造函数将其更改为true,而plane.cpp构造函数将其更改为false。我在sphere中就是这样做的: sphere::sphere(Vector3f Center, float Radius, Vector3f Ka, Vector3f Kd, Vector3f Ks, float Shininess) : shape(Ka, Kd, Ks, Shininess){ this->ka = Ka; this->kd = Kd; this->ks = Ks; this->radius = Radius; this->center = Center; this->shininess = Shininess; this->isRound = true; },c++,inheritance,boolean,C++,Inheritance,Boolean,在飞机上: plane::plane(Vector3f Ka, Vector3f Kd, Vector3f Ks, Vector3f Normal, Vector3f Point, float shininess) : shape(Ka, Kd, Ks, shininess){ this->shininess = shininess; this->ka = Ka; this->kd = Kd; this->ks = Ks; this->normal = Normal

在飞机上:

plane::plane(Vector3f Ka, Vector3f Kd, Vector3f Ks, Vector3f Normal, Vector3f Point, float shininess) : shape(Ka, Kd, Ks, shininess){
this->shininess = shininess;
this->ka = Ka;
this->kd = Kd;
this->ks = Ks;
this->normal = Normal;
this->point = Point;
this->isRound = false;
}

这就是我的形状.h的样子:

class shape
{
protected:
    Vector3f color;
public:
    Vector3f ka;
    Vector3f kd;
    Vector3f ks;
    int      shininess;
    bool isRound; ...
然而,无论我创建什么形状,它们都能获得真正的价值。
我做错了什么?

您的代码看起来是正确的。问题出在您发布的代码之外。球体和形状是否可能同时定义isRound成员?看起来正常。粘贴编译并运行的代码?您如何知道自己的形状?找不到虚拟函数…感谢stijn!就是这样,我在plane.h和sphere.h文件中也有isRound bool。删除它们解决了问题!