cout它的构造函数中的一个实例

时间:2014-04-29 04:06:33

标签: c++ class operator-overloading

我知道这可能听起来很奇怪,有办法解决这个问题。但我只是想知道在c ++中它是否可行。

class Item{
     public:
            string name;
     Item(string input){
            name = input
            cout << this;  // unfortunately the std::ostream& operator<<(std::ostream& outstream, Item* item) are not parsed by compiler yet. and this simply prints out its address.
                cout << *this; //I don't know how to override `cout << Item`.
     }
}

std::ostream& operator<<(std::ostream& outstream, Item* item){
    outstream << item->name;
    return outstream;
}

std::ostream& operator<<(std::ostream& outstream, Item& item){
    outstream << item.name;
    return outstream;
}

1 个答案:

答案 0 :(得分:1)

尝试以下

std::ostream & operator <<( std::ostream &outstream, const class Item &item );


class Item
{
     public:
            std::string name;
            Item( const std::string &input ) : name( input )
            {
                std::cout << *this;
            }
};

std::ostream & operator<<( std::ostream &outstream, const Item &item )
{
    outstream << item.name;
    return outstream;
}

或者,如果数据成员名称将被定义为私有,那么您可以编写

class Item
{
     private:
            std::string name;
     public:
            Item( const std::string &input ) : name( input )
            {
                std::cout << *this;
            }
           friend std::ostream & operator <<( std::ostream &outstream, const Item &item );

};

std::ostream & operator<<( std::ostream &outstream, const Item &item )
{
    outstream << item.name;
    return outstream;
}

以同样的方式重载运算符

std::ostream & operator <<( std::ostream &outstream, const class Item *item );

如果你需要的话。但事实上,没有必要重载此运算符。将操作符作为参数使用操作符就足够了。