C++ 中私有与受保护之间的区别
在这篇文章中,我们将了解 C++ 中私有且受保护的访问修饰符之间的区别。
私有访问修饰符
使用“私有”关键字声明它们,后跟“:”。
无法在类外部访问它们。
“private”关键字是一个访问修饰符,它确保只能由已声明它们的类成员访问类中的函数和属性。
只有成员函数或友元函数才能访问标记为“private”的数据。
示例
#include <iostream>
using namespace std;
class base_class{
private:
string my_name;
int my_age;
public:
void getName(){
cout << "Enter the name... ";
cin >> my_name;
cout << "Enter the age... ";
cin >> my_age;
}
void printIt(){
cout << "The name is : " << my_name << endl;
cout << "The age is: " << my_age << endl;
}
};
int main(){
cout<<"An object of class is created"<< endl;
base_class my_instance;
my_instance.getName();
my_instance.printIt();
return 0;
}输出
/tmp/u5NtWSnX5A.o An object of class is created Enter the name... Jane Enter the age... 34 The name is : Jane The age is: 34
受保护的访问修饰符
保护访问修饰符类似于私有访问修饰符。
使用“protected”关键字声明它们,后跟“:”。
声明为“Protected”的类成员无法在类外部访问。
可以在声明它们的类中访问它们。
它们也可以由父类包含“受保护”成员的派生类访问。
在使用继承概念时使用它们。
示例
#include <iostream>
using namespace std;
class base_class{
private:
string my_name;
int my_age;
protected:
int my_salary;
public:
void getName(){
cout << "Enter the name... ";
cin >> my_name;
cout << "Enter the age... ";
cin >> my_age;
}
void printIt(){
cout << "The name is : " << my_name << endl;
cout << "The age is: " << my_age << endl;
}
};
class derived_class : public base_class{
private:
string my_city;
public:
void set_salary(int val){
my_salary = val;
}
void get_data_1(){
getName();
cout << "Enter the city... ";
cin >> my_city;
}
void print_it_1(){
cout << "The salary is: " << my_salary << endl;
printIt();
cout << "The city is: " << my_city << endl;
}
};
int main(){
cout<<"Instance of derived class is being created.."<<endl;
derived_class my_instance_2 ;
my_instance_2.set_salary(100);
my_instance_2.get_data_1();
my_instance_2.print_it_1();
return 0;
}输出
/tmp/u5NtWSnX5A.o Instance of derived class is being created.. Enter the name... Jane Enter the age... 23 Enter the city... NewYork The salary is: 100 The name is : Jane The age is: 23 The city is: NewYork
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP