如何用过载输出来控制"这个"?

How to cout 'this' with overloaded output?

本文关键字:这个 控制 何用过 输出      更新时间:2023-10-16

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

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是一个指针。您的operator<<需要一个实际的Shape对象,而不是指针。

因此,您必须先取消引用指针:*this

或者只使用运算符<<

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