🎃个人专栏:
🐬 算法设计与分析:算法设计与分析_IT闫的博客-CSDN博客
🐳Java基础:Java基础_IT闫的博客-CSDN博客
🐋c语言:c语言_IT闫的博客-CSDN博客
🐟MySQL:数据结构_IT闫的博客-CSDN博客
🐠数据结构:数据结构_IT闫的博客-CSDN博客
💎C++:C++_IT闫的博客-CSDN博客
🥽C51单片机:C51单片机(STC89C516)_IT闫的博客-CSDN博客
💻基于HTML5的网页设计及应用:基于HTML5的网页设计及应用_IT闫的博客-CSDN博客
🥏python:python_IT闫的博客-CSDN博客
欢迎收看,希望对大家有用!
目录
🎯第一题:
🎯 第二题:
🎯 第三题:
🎯 答案:
💻第一题:
💻第二题:
💻第三题:
🎯第一题:
现有一学生类定义, 分别实现类的构造函数、拷贝构造函数(深拷贝)、析构函数及显示函数;分别用构造函数及拷贝构造函数创建对象,并输出对象信息。效果如图:
🎯 第二题:
声明一个Student类,在该类中包括数据成员name(姓名),score(分数)、两个静态数据成员total_score(总分)和count(学生人数);一个静态成员函数average()用于求全班成绩的平均值。在main函数中,输入某班(3个)同学的姓名成绩,输出全班学生的成绩之和及平均分。效果如图:
🎯 第三题:
设计一个坐标系点类Point,友元函数dis计算给定两个坐标点的距离;在主程序中创建类Point的两个点对象p1和p2;计算两个点之间距离并输出。效果如图:
🎯 答案:
💻第一题:
#include <iostream>
#include <cstring>
using namespace std;
class Student {
public:
Student(int id,string name,char* addr);
Student(const Student& other);
~Student();
void show();
private:
int _id;
string _name;
char *_addr;
};
Student::Student(int id,string name,char* addr) {
cout<<"调用构造函数"<<endl;
_id=id;
_name=name;
int len =strlen(addr)+1;
_addr=new char[len];
memset(_addr,0,len);
strcpy(_addr,addr);
}
Student::Student(const Student& another) {
cout<<"调用拷贝构造函数"<<endl;
_id=another._id;
_name=another._name;
int len=strlen(another._addr)+1;
_addr=new char[len];
strcpy(_addr,another._addr);
}
void Student::show() {
cout<<_id<<" "<<_name<<" "<<_addr<<endl;
}
Student::~Student() {
cout<<"调用析构函数"<<endl;
if(_addr!=NULL)
delete []_addr;
}
int main() {
char *p = "beijing";
Student stuA(123456,"zhangsan",p);
cout<<"stuA:";
stuA.show();
Student stuB(stuA); //使用sheepA初始化新对象sheepB
cout<<"stuB:";
stuB.show();
return 0;
}
💻第二题:
#include <iostream>
using namespace std;
class Student {
public:
Student(string _name,int _score);
static float average();
static float total_score;
static int count;
private:
string name;
float score;
};
Student::Student(string _name,int _score){
name=_name;
score=_score;
total_score+=score;
count++;
}
float Student::total_score=0.0;
int Student::count=0;
float Student::average(){
return (total_score/count);
}
int main() {
string name;
float score;
cout<<"input name,socre:";
cin>>name>>score;
Student stu1(name,score);
cout<<"input name,socre:";
cin>>name>>score;
Student stu2(name,score);
cout<<"input name,socre:";
cin>>name>>score;
Student stu3(name,score);
cout<<"total_socre:"<<Student::total_score<<",average:"<<Student::average()<<endl;
return 0;
}
💻第三题:
#include <iostream>
#include <cmath>
using namespace std;
class Point {
friend float dis(Point &p1,Point &p2);
public:
Point(float x,float y);
~Point();
private:
float _x;
float _y;
};
Point::Point(float x=0,float y=0):_x(x),_y(y) {
cout<<"初始化坐标点"<<endl;
}
Point::~Point() {}
float dis(Point &p1,Point &p2) {
float d=sqrt((p1._x-p2._x)*(p1._x-p2._x)+(p1._y-p2._y)*(p1._y-p2._y));
return d;
}
int main() {
Point p1(5,5);
Point p2(10,10);
float distance=dis(p1,p2);
cout<<"两点间距离是:"<<distance<<endl;
return 0;
}