正在访问类实例的属性
Accessing property of class instance
我试图得到一个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)等
相关文章:
- C++如何将同一类的实例作为属性
- 无法使用 SWIG 在 Python 中实例化C++类(获取属性错误)
- 返回的指针属性中类实例上的矢量属性消失
- 依赖于类成员属性的类实例成员
- 类实例的C++/向量作为另一个类的属性
- 将成员函数分配给实例成员的属性
- 通过从类 B 访问类 A 实例来更改该实例的属性
- 从另一类获得与属性相同的类实例
- 如何使用结构实例的名称调用其属性
- 正在访问类实例的属性
- 在类中创建公共属性,该类是此类的实例
- 如果我在一个类中有一个静态属性,并创建该类的许多新实例
- 是否可以为现有类的实例绑定新属性,例如 c++ 中的 JavaScript?
- 类属性包括模板类的实例(错误 C3857)
- C++ QML 插件,无法查看C++实例上的属性
- 使用OOP,当您有一个类的实例作为另一类的属性时,如何可能只在第二个类中实例化它
- 在运行时将属性与类实例关联
- 正在获取ostream模板以打印指针列表中的实例属性
- 实现具有自动增量实例属性的类的最python的方式是什么?
- 如果某些实例不使用基类的属性,我应该继承子类吗?