简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM