不能重载运算符<<因为单身

时间:2017-11-23 16:28:23

标签: c++ printing singleton operator-overloading

我按照本教程创建了我的单例(我的类名为King):https://sourcemaking.com/design_patterns/singleton/cpp/2; 所以这是我的代码:

King.h:

#include "Generic_Piece.h"

class King : public Generic_Piece {
public:
     //public static accessor function
     static King *instance();


 protected:
     //singleton : define all constructors to be protected
     King(){}

 private:
     static King *k;

 };

//Print the king in green colour
namespace std{
    ostream& operator<<(ostream& out, const King& k);
}

King.cpp:

#include "King.h"

King *King::k = 0;
King *King::instance(){
    if(!k){
        k = new King();
        //the king is green
        k->setTeam(0);
    }
    return k;
}
//Printing the king
namespace std{
    ostream& operator<<(ostream& out, const King& k){
        out << "\033[32m" << "K" << "\033[0m";
        return out;
    }
}

正如您所看到的,我的问题是我想要重载<<运算符以打印绿色K.我在主要调用它:

std::cout << King::instance() << std::endl;

但它打印出地址0x55d7a133f280。我想问题是我对单身人士的使用。我想我可以使用King::print()函数进行打印,但我更愿意重载<<运算符。你有什么想法吗?

1 个答案:

答案 0 :(得分:2)

King::instance返回一个指针。因此,当你写

std::cout << King::instance() << std::endl;

调用operator <<的不同重载 - 采用void*的重载。要使用您的运算符打印实例,请添加derererence:

std::cout << *King::instance() << std::endl;

更好的是,让King::instance()返回对King的引用:

King& King::instance(){
    if(!k){
        k = new King();
        //the king is green
        k->setTeam(0);
    }
    return *k;
}

现在,operator <<的原始通话会产生正确的结果。