C++实验22

一、类中类型转换函数重载

#include<iostream>
using namespace std;
#include<string>

class student
{
    int idnum;
    char name[20];
    bool gender;
    int age;
    float grade_eng;
    float grade_math;
    float grade_phy;
    float grade_cpp;
public:
    student(int a, char *b, bool c, int d, float e, float f, float g, float h)
    {idnum=a;strcpy(name,b);gender=c;age=d;grade_eng=e;grade_math=f;grade_phy=g;grade_cpp=h;}
    void show()
    {
        cout<<"ID\tName\tSex\tAge\tEnglish\tMath\tPhysics\t\C++"<<endl;
        cout<<idnum<<'\t'<<name<<'\t';
        if(gender)
            cout<<"Man\t";
        else
            cout<<"Woman\t";
        cout<<age<<'\t'<<grade_eng<<'\t'<<grade_math<<'\t'<<grade_phy<<'\t'<<grade_cpp<<endl;
    }
    operator float()
    {
        return (grade_eng+grade_math+grade_phy+grade_cpp)/4;
    }
};

void main()
{
    student stu(20170101,"Zhangsan",true,20,90.1,80,75.4,100);
    stu.show();
    cout<<float(stu)<<endl;
}

二、字符串类中运算符重载

//+=,==,-=,=,operator int

#include<iostream>
using namespace std;
#include<string.h>

class mystring
{
    char *str;
public:
    mystring(char *p)
    {
        str=new char[strlen(p)+1];
        strcpy(str,p);
    }
    mystring(){str=NULL;}
    ~mystring() {delete []str;}
    void show()
    {
        if(str)
            cout<<str<<endl;
        else
            cout<<"This str is NULL!\n";
    }
    mystring operator =(mystring &a)   
    //返回值未使用引用,因已自定义深拷贝构造函数
    {
        if(str)
        {
            cout<<"if str";
            delete []str;
        }
        str=new char[strlen(a.str)+1];
        strcpy(str,a.str);
        return *this;
    }
    mystring & operator +=(mystring &a)
    {
        char *temp = new char[strlen(a.str)+strlen(str)+1];
        strcpy(temp,str);
        strcat(temp,a.str);
        delete []str;
        str=temp;
        return *this;
    }
    mystring(mystring & a)
    {
        str=new char[strlen(a.str)+1];
        strcpy(str,a.str);
    }
    friend bool operator ==(mystring &a,mystring &b);
};
bool operator ==(mystring &a, mystring &b)
{
    if(strlen(a.str)!=strlen(b.str))
        return false;
    for(int i=0;i<strlen(a.str);i++)
        if(a.str[i]!=b.str[i])
            return false;
    return true;
}
void main()
{
    mystring a("张三");                          
    a.show();
    mystring b("李四");
    b.show();
    b+=a;
    b.show();
    mystring c(a);
    cout<<(a==b)<<endl;
    cout<<(a==c)<<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值