如何cout'这个'超载输出?

时间:2016-03-06 16:28:55

标签: c++

在下面的示例中,如何引用当前对象实例以获取使用输出重载的机会?

class Shape {
    private:
        double _length, _width;
        double straight(double value) {
            if (value<0) { return -value; }
            if (value==0) { return 1; }
            return value;
        }
    public:
        Shape() { setDims(1,1); }
        Shape(double length, double width) {
            setDims(length, width); }
        void setDims(double length, double width) {
            _length=straight(length); _width=straight(width); }

        friend ostream &operator<<(ostream &output, Shape &S) {
            output << S._length << "," << S._width; return output; }

        void display() { cout << [THIS] << endl; }
};

int main(int argc, const char * argv[]) {

    Shape s1; s1.display();
    return 0;
}

3 个答案:

答案 0 :(得分:5)

就像这样:

void display() { cout << *this << endl; }

答案 1 :(得分:1)

this是一个指针。您的operator<<想要一个实际的Shape对象,而不是指针。

所以你必须先取消引用指针:*this

答案 2 :(得分:1)

或者只使用运算符&lt;&lt;

#include <iostream>

using namespace std;

class Shape {
private:
    double _length, _width;
    double straight(double value) {
        if (value<0) { return -value; }
        if (value == 0) { return 1; }
        return value;
    }

public:
    Shape() { setDims(1, 1); }
    Shape(double length, double width) {
        setDims(length, width);
    }
    void setDims(double length, double width) {
        _length = straight(length); _width = straight(width);
    }

friend ostream &operator<<(ostream &output, Shape &S) {
    output << S._length << "," << S._width; return output;
}

int main(int argc, const char * argv[]) {

    Shape s1;

    std::cout << s1 << std::endl;
}