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

时间:2016-11-10 19:57:06

标签: c++ cocos2d-x

我有一个包含一些游戏关卡设置的课程。

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.

我在这里缺少什么?

1 个答案:

答案 0 :(得分:3)

怀疑CCLOG()使用与<x>printf()函数系列相同的格式规则,您需要传递格式说明符为const char*的{​​{1}}。

您的%s会返回getImgName()值,但不会与std::string直接兼容。

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

const char*

此外,您可以更清楚地改进getter / setter函数,指定 CCLOG("Image Name: %s", stagesArr[0].getImgName().c_str()); 适用性:

const

注意:
作为一种风格问题,您可以省略c ++中getter / setter函数的 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; } // ^^^^^ / 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; } 后缀消除类成员变量的歧义:

_