gpt4 book ai didi

c++ - std::ostream& operator<<(std::ostream&, const T&) 未被覆盖

转载 作者:太空宇宙 更新时间:2023-11-04 14:22:23 24 4
gpt4 key购买 nike

偶尔我会写一个类(T 说)并尝试覆盖 std::ostream& operator<<(std::ostream&, const T&) 但它不适用于某些类。这是一个(简化的)类的示例,它对我不起作用。

class ConfigFile {
public:
explicit ConfigFile(const std::string& filename);
virtual ~ConfigFile();

bool saveToDisk() const;
bool loadFromDisk();

std::string getSetting(const std::string& setting, const std::string& section="Misc") const;
void setSetting(std::string value, const std::string& name, const std::string& section ="Misc", bool updateDisk = false);

inline const SettingSectionMap& getSettingMap() const {
return mSettingMap;
}

private:
std::string mSettingFileName;
SettingSectionMap mSettingMap;

#if defined(_DEBUG) || defined(DEBUG)
public:
friend std::ostream& operator<<(std::ostream& output, const ConfigFile& c) {
output << “Output the settings map here”;
return output;
}
#endif
}

我很确定 explicit 关键字会阻止转换构造函数的情况,但它确实像它一样,因为当我做类似的事情时

std::cout << config_ << std::endl;

它的输出类似于:0x100588140。但是后来我在另一个类(class)做了同样的事情,就像下面的类(class)一样,一切正常。

class Stats {
Stats() {};

#if defined(_DEBUG) || defined(DEBUG)
friend std::ostream& operator<<(std::ostream& output, const Stats& p) {
output << "FPS Stats: " << p.lastFPS_ << ", " << p.avgFPS_ << ", " << p.bestFPS_ << ", " << p.worstFPS_ << " (Last/Average/Best/Worst)";
return output;
};
#endif
};

感谢您的帮助。

编辑:为了解决这个问题,我现在将以下内容添加到我的所有类(class)中:

#if  defined(_DEBUG) || defined(DEBUG)
public:
friend std::ostream& operator<<(std::ostream& output, const ConfigFile& c);
friend std::ostream& operator<<(std::ostream& output, ConfigFile* c) {
output << *c;
return output;
}
#endif

最佳答案

尝试将签名更改为 const 指针:

std::ostream& operator<<(std::ostream& output, const ConfigFile* c);

关于c++ - std::ostream& operator<<(std::ostream&, const T&) 未被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6519068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com