C++之类访问修饰关键字

C++之类访问修饰关键字

public在前面博客中已经出现多次,这里我们只记录private和protected关键字的用法。

private访问关键字

#include <iostream>
#include <cstring>

using namespace std;

class Tprivate {
public:
    double get_width();

    void set_width(double w);

private:
    double width;
};

double Tprivate::get_width() {
    return width;
}

void Tprivate::set_width(double w) {
    width = w;
}

Tprivate t_private;

int main() {
    system("chcp 65001");
    double w = 20;
    t_private.set_width(w);
    double width = t_private.get_width();
    cout << "对象调用set_width为私有成员赋值:" << width << endl;
    return 0;
}
输出:
Active code page: 65001
对象调用set_width为私有成员赋值:20

一般,我们将成员函数定义为public,为外部提供调用,将成员变量定义为private,防止外部直接对内部成员变量进行修改,如果没有private,public,protected修饰关键字,则会默认为private。实例化对象后,不能直接使用对象点的方式对private修饰的成员变量进行赋值修改,但是可以通过调用公有的成员函数对private中定义的变量赋值。

protected访问关键字

#include <iostream>

using namespace std;

class Father {
protected:
    int height;
};

class Children : Father {
public:
    void set(double h);

    double get();
};

//Father的派生类
void Children::set(double h) {
    height = h;
}

double Children::get() {
    return height;
}

Children children;

int main() {
    system("chcp 65001");
    double h = 10;
    children.set(h);
    double height = children.get();
    cout << "子类访问父类的protected成员变量并赋值:" << height << endl;
}
输出:
Active code page: 65001
子类访问父类的protected成员变量并赋值:10

protected(受保护)成员变量或函数与私有成员十分相似,但有一点不同,protected(受保护)成员在派生类(即子类)中是可访问的。
1.private 成员只能被本类成员(类内)和友元访问,不能被派生类访问;
2.protected 成员可以被派生类访问。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值