Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
99 views
in Technique[技术] by (71.8m points)

c++ - Declaring multiple object pointers on one line causes compiler error

when I do this (in my class)

public:
    Entity()
    {
        re_sprite_eyes = new sf::Sprite();
        re_sprite_hair = new sf::Sprite();
        re_sprite_body = new sf::Sprite();
    }

private:
    sf::Sprite* re_sprite_hair;
    sf::Sprite* re_sprite_body;
    sf::Sprite* re_sprite_eyes;

Everything works fine. However, if I change the declarations to this:

private:
    sf::Sprite* re_sprite_hair, re_sprite_body, re_sprite_eyes;

I get this compiler error:

error: no match for 'operator=' in '((Entity*)this)->Entity::re_sprite_eyes = (operator new(272u), (<statement>, ((sf::Sprite*)<anonymous>)))

And then it says candidates for re_sprite_eyes are sf::Sprite objects and/or references.

Why does this not work? Aren't the declarations the same?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

sf::Sprite* re_sprite_hair, re_sprite_body, re_sprite_eyes;

Does not declare 3 pointers - it is one pointer and 2 objects.

sf::Sprite* unfortunately does not apply to all the variables declared following it, just the first. It is equivalent to

sf::Sprite* re_sprite_hair;
sf::Sprite re_sprite_body;
sf::Sprite re_sprite_eyes;

You want to do:

sf::Sprite *re_sprite_hair, *re_sprite_body, *re_sprite_eyes;

You need to put one star for each variable. In such cases I prefer to keep the star on the variable's side, rather than the type, to make exactly this situation clear.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...