第一题
定义一个学生类 Student ,要求如下:
设计私有数据成员:
①年龄 int age; ②姓名 char *name;
公有成员函数:
①构造函数 带参数的构造函数 Student(int m,char *n) ;
②不带参数的构造函数 Student ( ) ;
③析构函数 ~ Student ( ) ; 释放由 name 申请的动态空间
④改变数据成员值函数 void SetMember ( int m,char *n ) ;
⑤获取年龄的成员函数 int Getage ( ) ;
⑥获取名字的成员函数 char *Getname ( ) ;
代码
#include<iostream>
#include<string.h>
using namespace std;
class Student
{
private:
int age;
char *name=new char[10];
public:
Student (int m,const char *n)
{
age=m;
strcpy(name,n);
}
Student ()
{
age=0;
strcpy(name,"unnamed");
}
~Student()
{
delete []name;
}
void SetMember (int m,const char *n)
{
age=m;
strcpy(name,n);
}
int Getage ()
{
return age;
}
char *Getname ()
{
return name;
}
};
int main()
{
Student stu[3]={Student(13,"wang")};
stu[2].SetMember(12,"zhang");
for(int i=0; i<3;i++)
cout<<stu[i].Getage( )<<","<<stu[i].Getname( )<<"\n";
return 0;
}
第二题
设计一个Car类,它的数据成员要能描述一辆汽车的品牌,型号,出厂年份和价格,成员函数包括提供合适的途径来访问数据成员,在main()函数中定义类的对象并调用相应成员函数。
设计私有数据成员:
string brand; 或者char *brand;
string type; 或者char *type;
int year;
double price;
公有成员函数:
构造函数 :默认品牌undefinition,默认型号undefinition,默认年份2000,默认价格 0;
获取数据成员的函数:
代码
#include<iostream>
using namespace std;
class Car
{
private:
string brand;
string type;
int year;
double price;
public:
Car(string b="undefinition",string t="undefinition",int y=2000,double p=0)
{
brand=b;
type=t;
year=y;
price=p;
}
string GetBrand()
{
return brand;
}
string GetType()
{
return type;
}
int GetYear()
{
return year;
}
double GetPrice()
{
return price;
}
};
int main()
{
Car car1("FIAT","Palio",2021,6.5);
cout<<car1.GetBrand()<<" "<<car1.GetType()<<" "<<car1.GetYear() <<" " <<car1.GetPrice()<<endl;
Car car2;
cout<<car2.GetBrand()<<" "<<car2.GetType()<<" "<<car2.GetYear()<<" " <<car2.GetPrice()<<endl;
return 0;
}