(对象)不命名类型.怎么回事

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

本文关键字:类型 怎么回事 对象      更新时间:2023-10-16

我认为代码最能说明问题

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"
};

错误说对象没有命名类型,但奇怪的是,CodeBlocks将麻烦的tekstura和TenBlok视为有效的对象,因为这些对象包含id提示函数

不能使用语句

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"

在类定义中。它们不是声明。您可以在成员函数的定义中包含此类语句,但不能在类本身中包含此类语句。

一个更简单的类,它将失败并出现类似的错误:

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

若要初始化i(或执行类似的语句(,请使用构造函数。

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

对于您的课程,您可能需要:

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);
   }
};