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 成员可以被派生类访问。