1 题目
2 分析
2.1 基础知识
- 可以在类的外部使用范围解析运算符
::
定义类成员函数:void Cude::get_width(){ return width; };
- 调用类成员函数:
Cube x; x.get_width();
- 类访问修饰符:
public
:公有,谁都可以访问(定义函数)private
:仅类(自己)和友元函数可以访问(定义数据)protected
:仅类、友元函数、派生类(即子类)中是可访问的
- 继承方式:
- public 继承:基类 public 成员,protected 成员,private 成员的访问属性在派生类中分别变成:public, protected, private
- protected 继承:基类 public 成员,protected 成员,private 成员的访问属性在派生类中分别变成:protected, protected, private
- private 继承:基类 public 成员,protected 成员,private 成员的访问属性在派生类中分别变成:private, private, private
- 构造函数除了常见的写法,还有一种初始化列表的写法:
Line::Line(double len){
this->length=len;
}
Line::Line(double len):length(len){
}
Line::Line(int a,int b,int c){
this->x=a;
this->y=b;
this->z=c;
}
Line::Line(int a,b,c):x(a),y(b),z(c){
}
2.2 本题
考察对于类的构造函数、private、public、函数的语法。灰常简单。
3 AC代码
#include <iostream>
using namespace std;
class Cube {
// write your code here......
private:
int length,width,height;
public:
Cube(){ }//构造函数
void setLength(int l){
length=l;
}
void setWidth(int w){
width=w;
}
void setHeight(int h){
height=h;
}
int getLength(){
return length;
}
int getHeight(){
return height;
}
int getWidth(){
return width;
}
int getArea(){
return 2*(length*width+length*height+width*height);
}
//计算体积(长*宽*高)
int getVolume(){
return length*width*height;
}
};
int main() {
int length, width, height;
cin >> length;
cin >> width;
cin >> height;
Cube c;
c.setLength(length);
c.setWidth(width);
c.setHeight(height);
cout << c.getLength() << " "
<< c.getWidth() << " "
<< c.getHeight() << " "
<< c.getArea() << " "
<< c.getVolume() << endl;
return 0;
}