• 主要区别在于派生类可以访问基本的Protected成员和方法,而无法访问基本的private成员和方法,其余是一样的。
  • 实例代码
// VBaseTime.cpp : 定义控制台应用程序的入口点。
// STL标准库使用

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <Windows.h>
using namespace std;

class Person{
public:
Person(){
cout << "初始化Person" << endl;
}
~Person(){
cout << "释放" << endl;
}
private:
void ShowPrivate(){
cout << "展示Private方法" << endl;
}
protected:
void ShowProtected(){
cout << "展示Protect方法" << endl;
}
};

class Man: public Person
{
public:
Man(){
cout << "初始化Man" << endl;
}
~Man(){
cout << "释放Man" << endl;
}
void testDemo(){
ShowProtected();
}
};

void demo()
{
unique_ptr<Man> mp(new Man());
//Man * mp = new Man();
mp->testDemo();
}

int _tmain(int argc, _TCHAR* argv[])
{
demo();
system("pause");
return 0;
}

简单说明一下,创建了父类​​Person​​​和子类​​Man​​​,子类继承了父类的ShowProtected方法,中间也使用智能指针 防止内存泄漏问题
运行结果:

C++ Protected和Private的区别_#include