上嵌学习笔记

C++基础-(重载)

2016-11-14  本文已影响10人  I踏雪寻梅

C++基础

重载

  1. 哪些运算符可以被重载:::,.,->,*,?:不能被重载
  2. 重载操作符的标志(operator)
#include <iostream>
using namespace std;
int a1=12,b1=13,c1;
class test
{
    int m_z;
    public:
        test(int z)
        {
            m_z=z;
        }
        test()
        {
            m_z=10;
        }
        int getz()
        {
            return m_z;
        }
        void setz(int z)
        {
            m_z=z;
        }
};
test a2(10),b2(5),c2;
test  operator+(test t1,test t2)
{
    return t1.getz()+t2.getz();
}
int main(int argc,char **argv)
{
    c1=a1+b1;//operator+(a1,b1);=>operator+(int i1,int i2);
    c2=a2+b2;//operator+(a2+b2);=>operator+(test t1,test t2);//这样编不过
    cout<<"c1="<<c1<<endl;
    cout<<"c2="<<c2.getz()<<endl;
}
/*
int operator+(test t1,test t2)
{
    return t1.getz()+t2.getz();
}
c1=a2+b2;//operator+(a2+b2);=>operator+(test t1,test t2);//这样编不过
cout<<"c1="<<c1<<endl;*/
#include <iostream>
using namespace std;
int a1=12,b1=13,c1;
class test
{
    int m_z;
    public:
        test(int z)
        {
            m_z=z;
        }
        test()
        {
            m_z=10;
        }
        int getz()
        {
            return m_z;
        }
        void setz(int z)
        {
            m_z=z;
        }
        int  operator+(test t2)//作为成员的运算符比之作为非成员的运算符,在声明和定义时,形式上少一个参数。
        {
            return  m_z+t2.m_z;
        }
};
test  a2(10),b2(5),c2; 
int main(int argc,char **argv)
{
    c1=a1+b1;//operator+(a1,b1);=>operator+(int i1,int i2);
    c1=a2+b2;//operator+(a2+b2);=>operator+(test t1,test t2);//这样编不过
    cout<<"c1="<<c1<<endl;
}
#include <iostream>
using namespace std;
int a1=12,b1=13,c1;
class test
{
    int m_z;
    public:
        test(int z)
        {
            m_z=z;
        }
        test()
        {
            m_z=10;
        }
        int getz()
        {
            return m_z;
        }
        void setz(int z)
        {
            m_z=z;
        }
        int  operator+(test t2)
        {
            return  m_z+t2.m_z;
        }
        friend test &operator++(test &t);//前缀++
        friend test operator++(test &t,int);//后缀++
        friend ostream &operator<<(ostream &c,test &z);
};
test  a2(10),b2(5),c2;
test &operator++(test &t)//前缀++
{
    ++t.m_z;
    return t;
}
test operator++(test &t,int)//后缀++
{
    test z(t.m_z);
    ++t.m_z;
    return z;
}
ostream &operator<<(ostream &c,test &z)
{
    c<<z.m_z;
    return c;
}
int main(int argc,char **argv)
{
    c2=++a2;
    cout<<"a2="<<a2.getz()<<endl;
    cout<<"c2="<<c2.getz()<<endl;
    cout<<a2<<endl;//operator<<(cout,a2);=>operator<<(ostream& ,test &);
}
上一篇 下一篇

猜你喜欢

热点阅读