Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - (object) does not name a type. Whats going on?

I think the code shows the problem best

class blok
{ public:
    sf::RectangleShape TenBlok;
    int x,y;
    blok(int posX ,int posY)
 {
     x = posX;
     y = posY;
 }
 void place(int x,int y)
 {
        TenBlok.setPosition((float)x,(float)y)
 }
};

[...]

class Trawa : public blok
{

int id = 0;
sf::Texture tekstura;
tekstura.loadFromFile("trawa.png"); //<---- here it says "tekstura does not name a type"
TenBlok.setTexture(tekstura); //<---- here it says "TenBlok does not name a type"

};

Error says that the object doesnt name a type, but oddly enough CodeBlocks sees bother tekstura and TenBlok as vaild objects becouse id hints functions those objects contain

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You cannot use statements

tekstura.loadFromFile("trawa.png"); //<---- here it says "tekstura does not name a type"
TenBlok.setTexture(tekstura); //<---- here it says "TenBlok does not name a type"

in the class definition. They are not declarations. You can have such statements inside the definition of a member function, but not the class itself.

A simpler class that will fail with similar errors:

struct Foo
{
   int i;
   i = 10;
};

To initialize i (or execute similar statements), use a constructor.

struct Foo
{
   int i;
   Foo() { i = 10; }  // For demonstration. It will be better to initialize
                      // i using Foo() : i(10) {}
};

For you class, you probably need:

class Trawa : public blok
{
   int id = 0;
   sf::Texture tekstura;

   Trawa() : blok(0, 0)  // Assume position to be (0, 0)
   {
      tekstura.loadFromFile("trawa.png");
      TenBlok.setTexture(tekstura);
   }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...