一、定义学生类Student:每个学生的信息包含有姓名(字符指针)和成绩(int类型),定义两个构造函数:
1、 定义带两个参数的构造函数,在构造函数中为保存姓名信息的字符指针开辟空间,并向空间中存入表示姓名的字符串。
2、 定义拷贝构造函数,完成深拷贝
3、 定义析构函数,释放资源
4、 统计学生的总人数
编写程序,使用以上定义的三种函数。
使用的主函数进行测试,代码如下:
int main()
{
Student stu1("John", 98);
Student stu2(stu1);
Student *pstu=new Student("Tom",99);
cout<<"共"<<Student::getCount()<<"名学生。"<<endl;
delete pstu;
cout<<"共"<<Student::getCount()<<"名学生。"<<endl;
stu2.setName("Tom");
stu1.print_info();
stu2.print_info();
return 0;
}
输出(注意:逗号后有一空格):
共3名学生。
共2名学生。
name:John, score:98
name:Tom, score:98
#include<iostream> #include <string> using namespace std; class Student { public: Student(string name, int score) { num++; Name = new string(name); Score = score; } Student(const Student& stu) { num++; Name = new string(*stu.Name); Score = stu.Score; } void setname(string name) { *Name = name; } static int getCount() { return num; } void print_info() { cout << "name:" << *Name << ", " << "score:" << Score << endl; } string* Name; static int num; int Score; ~Student() { if (Name != NULL) { delete Name; Name = NULL; } num--; } }; int Student::num = 0; int main() { Student stu1("John", 98); Student stu2(stu1); Student* pstu = new Student("Tom", 99); cout << "共" << Student::getCount() << "名学生。" << endl; delete pstu; cout << "共" << Student::getCount() << "名学生。" << endl; stu2.setname("Tom"); stu1.print_info(); stu2.print_info(); return 0; }
二、设计一个点类Point,分别用成员函数、友元函数、普通函数求两点之间的距离。
使用如下主函数进行测试:
int main()
{
double x1,y1,x2,y2,result;
cin>>x1>>y1;
cin>>x2>>y2;
Point p1(x1, y1), p2(x2, y2);
result=p1.distance(p2);//成员函数
cout << "distance:" << result << endl;
result=mydistance(p1, p2);//普通函数
cout << "distance:" << result << endl;
result=f_distance(p1, p2);//友元函数
cout << "distance:" << result << endl;
return 0;
}
#include <iostream> #include <cmath> using namespace std; class Point { public: double x,y; Point(double a,double b):x(a),y(b){} double distance(const Point& a); friend double f_distance(const Point& a,const Point& b); }; double Point::distance(const Point& a) { return sqrt((a.x - x)*(a.x - x)+(a.y - y)*(a.y - y)); } double mydistance(const Point& a,const Point& b){ return sqrt((a.x - b.x)*(a.x - b.x)+(a.y - b.y)*(a.y - b.y)); } double f_distance(const Point& a,const Point& b){ return sqrt((a.x - b.x)*(a.x - b.x)+(a.y- b.y)*(a.y- b.y)); } int main() { double x1,y1,x2,y2,result; cin>>x1>>y1; cin>>x2>>y2; Point p1(x1, y1), p2(x2, y2); result=p1.distance(p2);//成员函数 cout << "distance:" << result << endl; result=mydistance(p1, p2);//普通函数 cout << "distance:" << result << endl; result=f_distance(p1, p2);//友元函数 cout << "distance:" << result << endl; return 0; }