首页 > 解决方案 > (object) 没有命名类型。这是怎么回事?

问题描述

我认为代码最能说明问题

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 提示这些对象包含的功能

标签: c++

解决方案


你不能使用语句

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

推荐阅读