默认构造函数在不应该被调用时被调用

时间:2014-07-18 05:29:20

标签: c++

所以我设法将我的问题缩小到这6行代码:

sf::Sprite charSpr;
charSpr.setTexture(charTex);

int _characterSets[] = {1, 8, 8};
AnimatedObject characterObj(&charSpr, 51, 75, 3, _characterSets);
PlayerObject character(&characterObj);

不知何故,通过这些行的过程总是会传递为AnimatedObject类调用默认构造函数,即使我只是调用AnimatedObject的构造函数,它只需要sf::sprite,两个intint数组。

PlayerObject构造函数

PlayerObject::PlayerObject(AnimatedObject* _animObj){
    anim = *_animObj;

    dynamic = false;
    for(int i = 0; i < 2; i++){
        position[i] = 0;
        velocity[i] = 0;
        acceleration[i] = 0;
        gravity[i] = 0;
    }
}

AnimatedObject构造函数

AnimatedObject::AnimatedObject(sf::Sprite* _s, int _w, int _h, int _st, int _fs[]){
    sprite = *_s;

    width = _w;
    height = _h;

    sets = _st;
    set = 1;

    frames.insert(frames.end(), &_fs[0], &_fs[sets]);
    frame = 1;
}
带有AnimatedObject默认构造函数的

错误消息为私有

In file included from PlayerObject.cpp:3:0:
AnimatedObject.hpp: In constructor ‘PlayerObject::PlayerObject()’:
AnimatedObject.hpp:9:3: error: ‘AnimatedObject::AnimatedObject()’ is private
   AnimatedObject();
   ^
PlayerObject.cpp:6:28: error: within this context
 PlayerObject::PlayerObject(){
                            ^
In file included from PlayerObject.cpp:3:0:
AnimatedObject.hpp: In constructor ‘PlayerObject::PlayerObject(AnimatedObject*)’:
AnimatedObject.hpp:9:3: error: ‘AnimatedObject::AnimatedObject()’ is private
   AnimatedObject();
   ^
PlayerObject.cpp:13:52: error: within this context
 PlayerObject::PlayerObject(AnimatedObject* _animObj){

1 个答案:

答案 0 :(得分:2)

您必须在初始化列表中初始化anim。否则它首先获得默认构造。所以,像这样:

PlayerObject::PlayerObject(AnimatedObject* _animObj) :
    anim(*_animObj)
{
    //snip
}

您应该对作为对象的所有成员变量执行此操作,以避免它们首先默认构造,然后分配给。对于像原始类型和指针这样的东西,你做的并不重要,但我认为大多数C ++编码器都希望在初始化列表中初始化所有成员变量,除了你想要默认值的那些要调用的构造函数,除非不实用(比如你的那些数组)。