简体   繁体   English

如何用过载输出提示“ this”?

[英]How to cout 'this' with overloaded output?

In the following example, how to refer to the current object instance to take opportunity to use the output overload? 在以下示例中,如何利用当前对象实例来利用输出重载?

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

像这样:

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

this is a pointer. this是一个指针。 Your operator<< wants an actual Shape object, not a pointer. 您的operator<<一个实际的Shape对象,而不是指针。

So you'll have to dereference the pointer first: *this . 因此,您必须首先取消引用指针: *this

Alternatively just use operator<< 或者只使用operator <<

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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