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

先看一个例子:

#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++在编译阶段就根据指针对应的类确定了成员的访问权限。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值