C ++类
2024-01-02 00:59:48
定义一个Person类,私有成员int age,string &name,定义一个Stu类,包含私有成员double *score,写出两个类的构造函数、析构函数、拷贝构造和拷贝赋值函数,完成对Person的运算符重载(算术运算符、条件运算符、逻辑运算符、自增自减运算符、插入/提取运算符)
#include <iostream>
using namespace std;
class person
{
int age;
string &name;
public:
person(string &a):age(18),name(a){}
person(int a,string &b):age(a),name(b){}
~person(){}
person(const person &other):age(other.age),name(other.name){}
person &operator=(const person&other)
{
this->age=other.age;
this->name=other.name;
return *this;
}
void show()
{
cout<<"age:"<<age<<endl<<"name:"<<name<<endl;
}
person operator+(const person&other)
{
int age=this->age+other.age;
static string name;
name = this->name+other.name;
return person(age,name);
}
bool operator==(person &other)
{
if((this->age==other.age)&&(this->name==other.name))
return true;
else
return false;
}
bool operator>(person &other)
{
if(this->age>other.age)
return true;
else
return false;
}
bool operator&&(person &other)
{
return (this->age&&other.age)||(this->name==other.name);
}
int getage(){return age;}
friend ostream &operator<<(ostream &out,person&c1);
friend istream &operator>>(istream &in,person &c1);
};
ostream &operator<<(ostream &out,person&c1)
{
out<<"age:"<<c1.age<<endl<<"name:"<<c1.name<<endl;
return out;
}
istream &operator>>(istream &in,person &c1)
{
in>>c1.age>>c1.name;
return in;
}
class stu
{
double *score;
person p1;
public:
stu(string &a):score(new double(12.5)),p1(a){}
stu(double a,string &b):score(new double(a)),p1(b){}
~stu(){delete score;}
stu(const stu&other):score(new double(*(other.score))),p1(other.p1){}
stu &operator=(const stu&other)
{
*(this->score)=*(other.score);
this->p1=other.p1;
return *this;
}
void show()
{
cout<<"score:"<<*score<<endl;
p1.show();
}
};
int main()
{
string a="zhangsan";
string b="lisi";
string c="wangwu";
stu a1(a);
a1.show();
cout<<endl;
person p1(a);
cout<<p1<<endl;
person p2(b);
cout<<p2<<endl;
person p3(c);
cout<<p3<<endl;
person p4=(p1+p2);
p4.show();
cout<<endl;
cout<<(p1==p2)<<endl;
cout<<(p1>p2)<<endl;
cout<<(p1&&p2)<<endl;
return 0;
}
文章来源:https://blog.csdn.net/m0_64059184/article/details/135329166
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!