NJUPT面向对象程序设计及C++mooc编程(第三章)--by sCh3n

第一题

定义一个学生类 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; 

}

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sh4ngchen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值