C++中基類和派生類的protcted成員的理解

看到《C++ primer》中文第4版的475頁時,不懂protected成員的使用範圍,特別是對這句:

    派生類只能通過派生類對象訪問其基類的protected成員,派生類對其基類類型對象的protected成員沒有特殊訪問權限

怎麼讀都覺得彆扭,於是自己編程試了一下,可能對protected成員的使用情況未考慮周全,但是也能反映一些問題。

代碼的解釋:

基類爲 shape,它有一個protected 成員爲

std::string shapename;
派生類circle和triangle都是對shape的繼承。

#include<iostream>
#include<string>

using namespace std;
using std::string;

class shape
{
private:
	int x,y;
protected:
	std::string shapename;
public:
	shape(int x0=0,int y0=0,std::string sn="any"):
		x(x0),y(y0),shapename(sn)
		{}
        void get_offset(int a,int b)
	{
		x=a;
		y=b;
	}
	std::string get_name(){return shapename; }
};
///*
class circle:public shape
{
	int centre_x,centre_y;
	public:
        void change_name(circle &d,shape &e)
	{
		std::string name="circle";
		d.shapename=name;
	//	e.shapename=name;//error
	}
		
};//*/

/*
class triangle:public shape
{
	int base,height;
	public:
        void change_name(circle &d,shape &e)
	{
		std::string name="triangle";
		d.shapename=name;
	//	e.shapename=name;//error
	}

};
*/
int main()
{
	shape tmp1;
	int a=1,b=2;
	tmp1.get_offset(a,b);
	std::cout<<"Print tmp1'soffset X and Y:"<<endl<<a<<endl<<b<<endl;
	
	std::string n;
	n=tmp1.get_name();
	cout<<"print tmp1's name:"<<endl<<n<<endl;


	
        circle tmp2;
        tmp2.change_name(tmp2,tmp1);
	n=tmp2.get_name();
        cout<<"print tmp2's name:"<<endl<<n<<endl;

        circle tmp3;
	n=tmp3.get_name();
	cout<<"before change name,tmp3's shapename is:"<<endl<<n<<endl;
	tmp3.change_name(tmp3,tmp1);
	n=tmp3.get_name();
        cout<<"after change name,tmp3's shapename is:"<<endl<<n<<endl;

/*
        triangle tmp4;
	tmp4.change_name(tmp2,tmp1);//error
	n=tmp2.get_name();
        cout<<"print the shape's name:"<<endl<<n<<endl;
	*/
	return 0;
}

代碼的運行結果:
Print tmp1'soffset X and Y:
1
2
print tmp1's name:
any
print tmp2's name:
circle
before change name,tmp3's shapename is:
any
after change name,tmp3's shapename is:
circle

分析

circle的成員函數chang_name()中對其基類的protected成員的訪問是不允許的。triangle與circle一樣,同時shape的派生類,但是circle的成員函數chang_name()不能訪問triangle的對象的protected成員,卻可以訪問circle對象的繼承自基類的protected成員。

結論

派生類中的成員函數可以訪問其自身的protected成員和從基類繼承而來的protected成員,也可以訪問與此派生類的對象(對象本身或其他對象)的protected成員

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章