您的位置:首页 > 编程语言 > C语言/C++

C++ 子类能不能改变父类中成员的访问权限?

2014-09-17 19:15 316 查看
先看一个例子:

#include <iostream>
using namespace std;

class Base
{
public:
Base(int i): common(i) {}
virtual ~Base() { cout << "destructing Base" << endl; }
virtual void Both() const { cout << "common=" << common << endl; }
virtual void ForA() = 0;
virtual void ForB() = 0;
protected:
int common;
};

class A: public Base
{
public:
A(int i, int aa): Base(i), a(aa) {}
~A() { cout << "destructing A" << endl; }
void ForA() { cout << "A: a=" << a << endl; }
private:
void ForB() { cout << "A: private ForB()" << endl; }

int a;
};

class B: public Base
{
public:
B(int i, int bb): Base(i), b(bb) {}
~B() { cout << "destructing B" << endl; }
void ForB() { cout << "B: b=" << b << endl; }
private:
void ForA() { cout << "B: private ForA()" << endl; }

int b;
};

int main()
{
Base* pBase = new A(0, 100);
pBase->ForA();
pBase->ForB(); // ok
delete pBase;

pBase = new B(0, 200);
pBase->ForA(); // ok
pBase->ForB();
delete pBase;

A* pA = new A(0, 111);
pA->ForA();
pA->ForB(); // error
delete pA;

return 0;
}
编译时报错:
> g++ -Wall test.cpp -o test
test.cpp: In function 'int main()':
test.cpp:26: error: 'virtual void A::ForB()' is private
test.cpp:58: error: within this context

屏蔽第 58 行之后的输出结果:

A: a=100
A: private ForB()
destructing A
destructing Base
B: private ForA()
B: b=200
destructing B
destructing Base
A: a=111
destructing A
destructing Base

也就是说 C++在编译阶段就根据指针对应的类确定了成员的访问权限。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: