的std :: ostream的和放;运算符<<(std :: ostream&,const T&)未被覆盖

时间:2011-06-29 10:21:07

标签: c++ operator-overloading

偶尔我会写一个类(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
}

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

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

1 个答案:

答案 0 :(得分:0)

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

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