有时我会编写一个类(T说)并尝试覆盖std :: ostream&运算符<

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 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
};


谢谢你的帮助。

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

#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);

10-08 07:33