现在的位置: 首页 > 综合 > 正文

C++ 重载运算符

2013年09月12日 ⁄ 综合 ⁄ 共 2042字 ⁄ 字号 评论关闭

C++ 重载运算符

 

[user:lib_hdmanage] cat example/test6.cpp
/// @file test6.cpp
/// @brief
/// @author Easton Woo
/// 0.01

#include <stdio.h>

class CGlobal
{
public:
    CGlobal(int i = 1) : m_value(i){};

    int m_value;
};

CGlobal & operator<<(CGlobal & main, CGlobal & param)  //相当于 main.func(param),返回值为main对象
{
    _print_int(param.m_value);
    main.m_value += param.m_value;
    _print_int(main.m_value);
    return main;
}

class CTest
{
public:
    CTest(int i = 1):m_value(i){};

    CTest & operator>>(CTest & ct)  // 有了this指针,第一个参数就可以不要了。
    {
        _print_int(ct.m_value);
        m_value += ct.m_value;
        _print_int(m_value);
        return *this;
    }
    int m_value ;
};

int main(int argc, char const* argv[])
{
#if 0
    CTest t1(1),t2(3),t3(5);
    t1>>t2>>t3; // 可以这么理解:t1>>t2相当于t1.func(t2),返回t1类对象后和>>t3组成新的函数t1.func(t2),再次返回t1类对象.

    _print_int(t1.m_value);
    _print_int(t2.m_value);
    _print_int(t3.m_value);
#else
    CGlobal t1(1),t2(3),t3(5);
    t1<<t2<<t3;

    _print_int(t1.m_value);
    _print_int(t2.m_value);
    _print_int(t3.m_value);
#endif

    return 0;
}

[user:lib_hdmanage] m example && ./example/test6.i386.elf
Makefile:4: test
Makefile:5: example
 [i386] make     -> hdmanage         example/test6.i386.elf ...
param.m_value = 3            example/test6.cpp : operator<<() : 18
main.m_value = 4            example/test6.cpp : operator<<() : 20
param.m_value = 5            example/test6.cpp : operator<<() : 18
main.m_value = 9            example/test6.cpp : operator<<() : 20
t1.m_value = 9            example/test6.cpp : main() : 53
t2.m_value = 3            example/test6.cpp : main() : 54
t3.m_value = 5            example/test6.cpp : main() : 55
[user:lib_hdmanage]

 

 

如果把#if 0 改成#if 1

 

[user:lib_hdmanage] m example && ./example/test6.i386.elf
Makefile:4: test
Makefile:5: example
 [i386] make     -> hdmanage         example/test6.i386.elf ...
ct.m_value = 3            example/test6.cpp : operator>>() : 31
m_value = 4            example/test6.cpp : operator>>() : 33
ct.m_value = 5            example/test6.cpp : operator>>() : 31
m_value = 9            example/test6.cpp : operator>>() : 33
t1.m_value = 9            example/test6.cpp : main() : 46
t2.m_value = 3            example/test6.cpp : main() : 47
t3.m_value = 5            example/test6.cpp : main() : 48

抱歉!评论已关闭.