20176510遥感一班李长宁

@李长宁的笔记:
c++中的类:
类是具有相同属性和行为的一组对象的集合,它为属于该类的全部对象提供了统一的抽象描述,其内部包括属性和行为两个主要部分。
利用类易于编写大型复杂程序,其模块化程度比C中采用函数更高。
类是一种用户自定义类型,声明形式:
class 类名称
{
public:
公有成员(外部接口)
private:
私有成员
protected:
保护型成员
};

1.定义一个dog类,包含age、weight属性,以及对这些属性的操作方法。实现并测试这个类。
#include

using namespace std;
class Dog
{
public:
Dog(int age0,double weight0);
void sr(int age1,double weight1);
void sc();
private:
int age;double weight;
};
Dog::Dog(int age0,double weight0)
{
age=age0;
weight=weight0;
}
void Dog::sr(int age1,double weight1)
{
age=age1;
weight=weight1;
}
void Dog::sc()
{
cout<<“age:”<<age<<endl<<“weight:”<<weight<<endl;
}
int main()
{
Dog dog1(0,0.0);
int a;
double b;
cin>>a>>b;
dog1.sr(a,b);
dog1.sc();
return 0;
}
2.设计并测试一个名为Rectangle 的矩形类,其属性为矩形的左下角与右上角两个点的坐标,能计算矩形的面积。
#include

using namespace std;

class Rectangle
{
public:
Rectangle(int a0,int b0,int c0,int d0);
void sr(int a,int b,int c,int d);
void sc();
private:
int x1,y1,x2,y2;
};
Rectangle::Rectangle(int a0,int b0,int c0,int d0)
{
x1=a0;
y1=b0;
x2=c0;
y2=d0;
}
void Rectangle::sr(int a,int b,int c,int d)
{
x1=a;
y1=b;
x2=c;
y2=d;
}
void Rectangle::sc()
{
int s;
s=(x2-x1)*(y2-y1);
cout<<“area:”<<s<<endl;
}
int main()
{
Rectangle z(0,0,0,0);
int m,n,p,q;
cin>>m>>n>>p>>q;
z.sr(m,n,p,q);
z.sc();

return 0;

}
3.创建一个Student类,该类中具有学生姓名,学号,性别,年龄,三科成绩、平均成绩等数据成员。在该类中定义成员函数实现相关信息的输入、输出。函数的原型声明放在类定义中。实现并测试这个类。
#include
using namespace std;
class Student
{public:
Student ()
{cout<<“请分别输入性别(女1男0)、姓名、学号、三科成绩”<<endl;
}
void nm(string a)
{name=a;
cout<<name<<endl;}
void num(long d){
number=d;
cout<<number<<endl;}
void gd(bool b)
{gender=b;
cout<<b<<endl;}
void sc(float c[3])
{int j, i;
for(i=0;i<3;i++)
score[i]=c[i];
for(j=0;j<3;j++)
cout<<score[j]<<endl;}
void aver(float d[3]){
float sum=0;
int q;
for(q=0;q<3;q++)
sum=sum+d[q];
ave=sum/3;
cout<<ave<<endl;}
private:
string name;long number;bool gender;float score[3];float ave;};
int main(){
Student stu;
int p;
float av,aa[3];
string na;
long nu;
bool gen;
cin>>gen>>na>>nu;
for(p=0;p<3;p++){
cin>>aa[p];}
stu.nm(na);
stu.num(nu);
stu.gd(gen);
stu.sc(aa);
stu.aver(aa);}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值