一、正方形边长
1、有成员属性width(长,int),成员属性height(宽,int)。
2、将width和height设置为私有属性,并提供公开的get,set函数。
3、有合理的构造函数,构造函数必须初始化height和width。
自定义类表示正方形(Square)继承自矩形(Rectangle)
要求:
1、改写父类的set函数,保证当正方形修改边长时长和宽都会改变。
2、有合理的构造函数,构造函数必须初始化Rectangle
代码示例:
#include <iostream>
#include <string>
using namespace std;
class Rectangle
{
private:
int width;
int height;
public:
Rectangle():width(),height(){}
Rectangle(int width,int height):width(width),height(height){}
void setWidth(int width)
{
this->width = width;
}
int getWidth()const
{
return width;
}
void setHeight(int height)
{
this->height = height;
}
int getHeight()const
{
return height;
}
};
class Square:public Rectangle{
public:
Square():Rectangle(){};
Square(int size):Rectangle{size,size}{}
void setWidth(int width)
{
Rectangle::setWidth(width);
Rectangle::setHeight(width);
}
void setHeight(int height)
{
Rectangle::setHeight(height);
Rectangle::setWidth(height);
}
};
int main()
{
Square s1(20);
s1.setHeight(10);
cout<<"正方形的边长:"<<s1.getHeight()<<endl;
cout<<"正方形的边长:"<<s1.getWidth()<<endl;
return 0;
}
注:int getHeight()const输出函数加const常量,表示该成员函数是一个常量成员函数,即在该函数中不能修改对象的成员变量。保证输出参数的稳定性。
运行结果:
正方形的边长:10
正方形的边长:10
二、学生信息
自定义类表示人(Person)。
要求:
1、有成员属性name(姓名,string),age(年龄,int)。
2、将name,age设为受保护属性。
3、有合理的构造函数,构造函数必须初始化name和age。
自定义类表示学生(Student)继承自人(Peron)。
要求:
1、添加属性score(成绩,int)。
2、将score设置为私有属性,并提供公开的get,set函数。
3、有公开的成员函数describe,可以用string描述学生的姓名,年龄和成绩。
建议describe的函数原型:string Student::describe()const;
4、有合理的构造函数,构造函数必须初始化Person和score
代码示例:
#include <iostream>
#include <string>
using namespace std;
class Person{
protected:
string name;
int age;
public:
Person():name(),age(){}
Person(string name,int age):name{name},age{age}{}
};
class Student:public Person
{
private:
int score;
public:
Student():Person(),score(){}
Student(string name,int age,int score):Person{name,age},score{score}{}
int getScore()const
{
return score;
}
void setScore()
{
this->score = score;
}
string describe()const
{
return "学生姓名:"+name+"学生年龄:"+to_string(age)+"学生成绩:"+to_string(score);
}
};
int main()
{
Student Student("gaoyinjie",27,102);
cout<<Student.describe()<<endl;
return 0;
}
运行结果:
学生姓名:gaoyinjie学生年龄:27学生成绩:102