std::ostream& operator<<(std::ostream&, const T&) not being overridden
Occasionally I have will write a class (T say) and attempt to override std::ostream& operator<<(std::ostream&, const T&) but it does not work on certain classes. Here is an example of a (simplified) class where it did not work for me.
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 st开发者_如何学编程d::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
}
I’m pretty sure the explicit keyword is going to prevent a converting constructor scenario but it sure acts like it because when I do something like
std::cout << config_ << std::endl;
It is outputting something like: 0x100588140. But then I do the same thing in another class like the one below and everything works fine.
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
};
Thanks for any help.
EDIT: To fix this I now add the following to all my classes:
#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
Try changing the signature to a const
pointer:
std::ostream& operator<<(std::ostream& output, const ConfigFile* c);
精彩评论