打印类

为了方便显示,总会有一种方法来使得类可以直接被print,cout等函数直接打印出来。

python中是__str__()和__repr__()方法。 其中__str__() 方法是针对用户的,使用print可以直接打印。而__repr__()是针对开发者的,主要是在交互界面进行打印。

java中是toString()方法。

而C语言中,主要是通过友元函数重载,即对于操作符<<的重载来实现的。主要方法如下:

class test{
public:
    test(int _x) : x(_x) {}
    friend ostream& operator << (ostream& os, const test& t){
        os << "test类中的值为" << t.x;
        return os;
    }
private:
    int x;
};

这样便可以直接通过cout来直接打印想要打印的信息。如:

test *t = new test(5)
cout << *t << endl;	//输出:test类中的值为5
delete t;
t = NULL;
原创文章 34 获赞 41 访问量 5969

猜你喜欢

转载自blog.csdn.net/qq_44844115/article/details/89053951