这个私有变量为什么会出现“未在此作用域中声明”的错误?

7

我目前正在尝试学习C++中的面向对象设计(熟悉Java),但遇到了一些困难。我正在尝试使用SFML构建一个游戏来学习这些原则。我有以下两个文件。

WorldObject.h

#ifndef WORLDOBJECT_H
#define WORLDOBJECT_H
#include <SFML/Graphics.hpp>
#include <string>
#include "ImageManager.h"

class WorldObject
{
 private:
  sf::Sprite _sprite;
  void SetImagePath(std::string path);
  sf::Sprite GetGraphic();
};
#endif

WorldObject.cpp

#include "WorldObject.h"
void WorldObject::SetImagePath(std::string path)
{
  _sprite.SetImage(*gImageManager.getResource(path));
}

sf::Sprite GetGraphic()
{
  return _sprite;
}

我认为这两个代码没有问题,但当我尝试编译它们时,g++会返回以下错误信息:

WorldObject.cpp: In function ‘sf::Sprite GetGraphic()’:
WorldObject.cpp:9: error: ‘_sprite’ was not declared in this scope
make: *** [WorldObject.o] Error 1

这段代码有什么问题?在理解正确的继承层次结构设置方式方面一直是游戏开发中最大的问题,但我知道这主要是因为我更习惯使用Java的继承模型而不是C++的多重继承模型。

5个回答

14

WorldObject.cpp 中定义的函数 GetGraphics 不是 WorldObject 类的成员函数。请使用:

sf::Sprite WorldObject::GetGraphic()
{
  return _sprite;
}

替代

sf::Sprite GetGraphic()
{
  return _sprite;
}

请注意,只有当程序中的某个地方调用了 WorldObject::GetGraphic 函数时,C++编译器才会抱怨其缺失。


2

sf::Sprite GetGraphic() 不正确,它声明了一个全局的 GetGraphic 函数。由于 GetGraphicclass WorldObject 的一个函数,应该是 sf::Sprite WorldObject::GetGraphic()


0
// `GetGraphic()` is a member function of `WorldObject` class. So, you have two options to correct-
//Either define the functionality of `GetGraphic()` in the class definition itself. 

#ifndef WORLDOBJECT_H
#define WORLDOBJECT_H
#include <SFML/Graphics.hpp>
#include <string>
#include "ImageManager.h"

class WorldObject
{
    private:
    sf::Sprite _sprite;
    void SetImagePath(std::string path);
    sf::Sprite GetGraphic()  // Option 1
    {
         return _sprite;
    }
};
#endif

//When providing the member function definition, you need to declare that it is in class scope.  
// Option 2 => Just prototype in class header, but definition in .cpp
sf::Sprite WorldObject::GetGraphic() 
{  
    return _sprite;  
}

0

我对C++不是很熟悉,但我认为在WorldObject.cpp中你需要使用WorldObject::GetGraphic而不是GetGraphic


0

我相信你的意思是:

sf::Sprite WorldObject::GetGraphic()

而不是

sf::Sprite GetGraphic()

在WorldObject.cpp文件中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接