正在访问类实例的属性

Accessing property of class instance

本文关键字:属性 实例 访问      更新时间:2023-10-16

我试图得到一个box2d模拟打印出x&y以与库中包含的helloWorld示例类似的方式浮动到屏幕上。我已经设法构建并链接到了库。

我有一个类定义了一个球,它应该从屏幕上的一个点落下,然后落下。但当我试图获得速度时,我无法访问成员数据。

objects.h内容

class Ball {
public:
bool m_contacting;
b2Body* m_body;
float m_radius;
public:
// Ball class constructor
Ball(b2World* m_world, float radius) {
m_contacting = false;
m_body = NULL;
m_radius = radius;
//set up dynamic body, store in class variable
b2BodyDef myBodyDef;
myBodyDef.type = b2_dynamicBody;
myBodyDef.position.Set(0, 20);
m_body = m_world->CreateBody(&myBodyDef);
//add circle fixture
b2CircleShape circleShape;
circleShape.m_p.Set(0, 0);
circleShape.m_radius = m_radius; //use class variable
b2FixtureDef myFixtureDef;
myFixtureDef.shape = &circleShape;
myFixtureDef.density = 1;
myFixtureDef.restitution = 0.83f;
m_body->CreateFixture(&myFixtureDef);
m_body->SetUserData( this );
m_body->SetGravityScale(5);//cancel gravity (use -1 to reverse gravity, etc)
}
~Ball(){}
};

实例化-球现在应该在模拟中

Ball* ball = new Ball(&world, 1);
balls.push_back(ball);

尝试打印身体的位置和角度。

b2Vec2 position = m_body->GetPosition();
float32 angle = m_body->GetAngle();
printf("%4.2f %4.2f %4.2fn", position.x, position.y, angle);

错误消息声明m_body未在作用域中声明。这似乎很简单,如果我在世界上定义一个身体,比如b2Body*body;并测试代码是否编译和运行,但由于我传递了一个空引用,所以会出现segfault。那么,我如何访问类实例的属性并将其打印出来呢。

我尝试过使用b2Vec2 position=Ball::m_body->GetPosition()&b2Vec2位置=球->GetPosition();但没有快乐。

m_body是Ball类的成员,您正试图在不使用Ball对象的情况下访问它。你需要做如下操作才能访问

ball->m_body->GetPosition();

或者访问存储在矢量中的球(假设您使用的是c++11)

for(auto& b : balls)
{
(*b).m_body->GetPosition();
}

for(int i = 0; i < balls.size(); ++i)
{
Ball* b = balls[i];
b->m_body()->GetPosition();
}

理想情况下,您不应该使用原始指针,而应该使用

Ball ball(&world, 1)
ball.m-body->GetPosition();

或者至少查看智能指针(unique_ptr)等