牛客网——类的基础知识点

文章介绍了C++中类的外部成员函数定义,类的访问修饰符(public,private,protected)的作用,以及不同继承方式对成员访问的影响。同时,讲解了构造函数的两种写法,并通过一个Cube类的例子展示了如何设置和获取类的私有成员变量以及计算面积和体积的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 题目

题目链接
在这里插入图片描述

2 分析

2.1 基础知识

  1. 可以在类的外部使用范围解析运算符 :: 定义类成员函数:void Cude::get_width(){ return width; };
  2. 调用类成员函数:Cube x; x.get_width();
  3. 类访问修饰符:
    • public:公有,谁都可以访问(定义函数)
    • private:仅类(自己)和友元函数可以访问(定义数据)
    • protected:仅类、友元函数、派生类(即子类)中是可访问的
  4. 继承方式:
    • public 继承:基类 public 成员,protected 成员,private 成员的访问属性在派生类中分别变成:public, protected, private
    • protected 继承:基类 public 成员,protected 成员,private 成员的访问属性在派生类中分别变成:protected, protected, private
    • private 继承:基类 public 成员,protected 成员,private 成员的访问属性在派生类中分别变成:private, private, private
  5. 构造函数除了常见的写法,还有一种初始化列表的写法:
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

MORE_77

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

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

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

打赏作者

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

抵扣说明:

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

余额充值