C++操作符重载

来源:互联网 发布:两游记配音软件 编辑:程序博客网 时间:2024/06/05 19:11

内容待完善。。。


1. 示例代码

#include <iostream>class Foo {public:    operator double() {        std::cout << "double()" << std::endl;        return 5.0;    }    operator int() {        std::cout << "int()" << std::endl;        return 3;    }};int main(){    Foo foo; // calling the implicit ctor    double d = foo;    int i = foo;    //float f = foo; // error C2440    std::cout << "d:" << d <<std::endl;    std::cout << "i:" << i <<std::endl;    return 0;}

2. 运行效果

double()int()d:5i:3

3. 另一个例子

class XYZ {public:    XYZ();    XYZ(double _x, double _y, double _z):x(_x), y(_y), z(_z){}    XYZ(const XYZ &a);    XYZ& operator=(const XYZ& rhs);    XYZ& operator+=(const XYZ& rhs);private:    double x;    double y;    double z;    friend XYZ operator+(XYZ& a, XYZ &b);};XYZ::XYZ():x(0), y(0), z(0){}XYZ::XYZ(const XYZ &a): x(a.x), y(a.y), z(a.z){}XYZ& XYZ::operator=(const XYZ &rhs){    if (this == &rhs) return *this;    x = rhs.x;    y = rhs.y;    z = rhs.z;    return *this;}XYZ& XYZ::operator+=(const XYZ& rhs){    this->x += rhs.x;    this->y += rhs.y;    this->z += rhs.z;    return *this;}XYZ operator+(XYZ& a, XYZ &b){    XYZ temp;    temp.x = a.x + b.x;    temp.y = a.y + b.y;    temp.z = a.z + b.z;    return temp;}int _tmain(int argc, _TCHAR* argv[]){    XYZ a(1,2,3);        XYZ b = a;    XYZ c;    c = a + b;    c += a;return 0;}




0 0
原创粉丝点击