用c++编写一个学生类的,包括姓名,学号和俩门成绩,要求输出学生数据,并计算平均分,定义一个拷贝函
用c++编写一个学生类的,包括姓名,学号和俩门成绩,要求输出学生数据,并计算平均分,定义一个拷贝函数,进行学生类的复制,并在主函数中进行测试...
用c++编写一个学生类的,包括姓名,学号和俩门成绩,要求输出学生数据,并计算平均分,定义一个拷贝函数,进行学生类的复制,并在主函数中进行测试
展开
展开全部
代码如下:
#include <string>
#include <iostream>
using std::string;
using std::cout; using std::cin; using std::endl;
using std::ostream;
class student
{
friend ostream & operator<<(ostream & os, const student &studData);
public:
student() = default;
student(const string &name, int number, double chjA = 0.0, double chjB = 0.0)
:mStrName(name), miNumber(number), mChengjiA(chjA), mChengjiB(chjB)
{}//显式构造函数
student(const student & rStData)//拷贝构造函数
{
if (this != &rStData)
{
mStrName = rStData.mStrName;
miNumber = rStData.miNumber;
mChengjiA = rStData.mChengjiA;
mChengjiB = rStData.mChengjiB;
}
}
double GetAveChengji()const
{
return (mChengjiA + mChengjiB) / 2;
}
public:
private:
string mStrName;
int miNumber = -1;
double mChengjiA = 0.0;
double mChengjiB = 0.0;
};
ostream & operator<<(ostream & os,const student &studData)//流输出操作符重载
{
os << "同学的姓名是:" << studData.mStrName
<< "。他/她的学号是:" << studData.miNumber
<< "。他/她第一科成绩为:" << studData.mChengjiA
<< ";第二科成绩为:" << studData.mChengjiA
<< ",平均成绩为:" << studData.GetAveChengji();
return os;
}
int main()
{
student st ={ "xx", 9989, 89.0, 78.4 };
student st2 = st;
cout << st << endl << st2;
return 0;
}
其实你还可以扩展很多,增加一些get,set等等
展开全部
#include <iostream>
#include <string>
using namespace std;
class Stu
{
public:
Stu(){}
Stu( const Stu &other)
{
name = other.name;
no = other.no;
chenji = other.chenji;
chenji2 = other.chenji2;
}
void show()
{
cout << "平均分:"<< ((chenji+chenji2)/2);
cout<< name << no << chenji << chenji2;
}
string name;
int no;
int chenji, chenji2;
};
int main()
{
Stu s1, s2;
s1.name = "xiaoming";
s1.no = 1;
s1.chenji = 70;
s1.chenji2 = 90;
s2 = s1;
s2.show();
return 0;
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询