从 Class C++ 获取成员字符串

Getting Member String from Class C++

我有一个 class,其中包含一些游戏关卡设置。

class Stage {
private: 
    int level;
    int stars;
    std::string imgName;

public:
    int getLevel(){ return level; };
    void setLevel(int n){ level = n; };

    int getStars(){ return stars; };
    void setStars(int n){ stars = n; };

    std::string getImgName(){ return imgName; };
    void setImgName(std::string name){ imgName = name; };
};

然后在我的程序中设置信息。

Stage* stagesArr = new Stage[3];

stagesArr[0].setLevel(0);
stagesArr[0].setStars(1200);
stagesArr[0].setImgName("stage0.png");

然后,如果我想获取此信息,字符串会给我一个奇怪的输出。

CCLOG("Level: %i", stagesArr[0].getLevel()); 
CCLOG("Required stars: %i", stagesArr[0].getStars());
CCLOG("Image Name: %s", stagesArr[0].getImgName());

//Level:0
//Required stars: 1200
//Image Name: T%s //Or just random stuff.

我在这里错过了什么?

怀疑CCLOG()使用与<x>printf()函数族相同的格式化规则,需要传递一个const char*,格式说明符%s

您的 getImgName() returns 是一个 std::string 值,它与 const char*.

不直接兼容

要实现后者,你应该调用std::string::c_str()函数:

 CCLOG("Image Name: %s", stagesArr[0].getImgName().c_str());

您还可以改进 getter/setter 函数,指定 constness 适用性更清晰:

   int getLevel() const { return level; }
               // ^^^^^^ 
   int getStars() const { return stars; }
               // ^^^^^^ 
   const std::string& getImgName() const { return imgName; }
// ^^^^^                       // ^^^^^^ 
void setImgName(const std::string& name) { imgName = name; }
             // ^^^^^ 

注:
作为一种风格,您可以在 c++ 中省略 getter/setter 函数的 get / set 前缀,因为签名已经足够明确:

int Level() const { return level; }
void Level(int n){ level = n; }

int Stars() const { return stars; }
void Stars(int n){ stars = n; }

const std::string& ImgName() const { return imgName; }
void ImgName(const std::string& name){ imgName = name; }

我个人喜欢的风格是使用小写字母并使用 _ 后缀消除 class 成员变量的歧义:

class Stage {
private: 
    int level_;
    int stars_;
    std::string img_name_;

public:
    int level() const { return level_; }
    void level(int n) { level_ = n; }

    int stars() const { return stars_; }
    void stars(int n){ stars_ = n; }

    const std::string& img_name() const { return img_name_; }
    void img_name(const std::string& name) { img_name_ = name; };
};