c++ 操作符重载

 /* file = main.cpp 涉及操作符重载,友元函数,重载类型转换*/
#include <iostream>
#include "testClass.h"
using namespace std;

int main()
{
    testClass tc1(2);
    testClass tc2(3);
    testClass tc3 = 1 + tc1 + tc2 + 4;// 重载加法
    testClass tc4 = 5 - tc2 - tc1 - 1;// 重载减法
    int a = tc1;// 重载了类型转换
    cout << "tc3:= " << tc3 << ", tc4:=" << tc4 << endl;
    // 重载了类型转换才能用下面这样的语句
    cout << "tc3 + t4 := " << tc3 + tc4 << endl;
    cout << "tc3 - t4 := " << tc3 - tc4 << endl;
    return 0;
}
/* file = testClass.h */
#ifndef TESTCLASS_H
#define TESTCLASS_H
#include <iostream>
class testClass
{
    public:
        testClass(int i);
        virtual ~testClass();
        testClass operator +(testClass & sf) const;
        testClass operator +(int j) const;
        testClass operator -(testClass & sf) const;
        testClass operator -(int j) const;
        operator int() const;// 重载类型转换;必须是成员函数,零参数,无返回值
        friend testClass operator +(int j, testClass & sf);
        friend testClass operator -(int j, testClass & sf);
        friend std::ostream & operator <<(std::ostream & os, testClass & sf);
    protected:
    private:
        int m_i;
};

#endif // TESTCLASS_H

/* file = testClass.cpp */
#include "testClass.h"

testClass::testClass(int i)
{
    this->m_i = i;
}

testClass::~testClass()
{
}

testClass testClass::operator +(testClass & sf) const{
testClass tc(this->m_i + sf.m_i);
return tc;
}

testClass testClass::operator +(int j) const{
testClass tc(this->m_i + j);
return tc;
}

testClass operator +(int j, testClass & sf){
   return sf + j;
}

testClass testClass::operator -(testClass & sf) const{
testClass tc(this->m_i - sf.m_i);
return tc;
}

testClass testClass::operator -(int j) const{
testClass tc(this->m_i - j);
return tc;
}

testClass operator -(int j, testClass & sf){
testClass tc(j - sf.m_i);
return tc;
}

testClass::operator int() const{
return this->m_i;
}

std::ostream & operator <<(std::ostream & os, testClass & sf){
    os << sf.m_i;
    return os;
}
共含三个文件,在winxp + codeblock 8.02 上测试通过,由于codeblock 新创建的类文件头文件放在include路径下,需要在project -> build options -> Search directories -> Compiler -> Add , 添加一个include 路径,否则codeblock 会报告找不到头文件"testClass.h"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值