c++ - (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 提示这些对象包含的功能
解决方案
你不能使用语句
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);
}
};
推荐阅读
- java - 从 Java 中的 Postgres 加载非物化数组
- matlab - 使用 matlab.mixins.Copyable 分配时是否自动复制
- javascript - 修改obj javascript中的项目
- arrays - 从另一个数组中删除一个元素数组
- javascript - 我如何总结这个对象数组?
- dialogflow-es - 带有 Webhook 客户端的 DialogFlow:错误 agent.getContext 不是 IncomingMessage.resp 的函数
- python - NotImplementedError:重载函数 Quantlib Python 的参数数量或类型错误
- python-3.x - 对生成器执行频率分布计数,并返回大于 n 的值
- html - 选择从 mysql 获取的值
- javascript - 使用 Angular Material 表,如何为忽略一列的表行设置点击事件处理程序