继承中的访问级别__建议自己实现

继承中的访问级别

  • 子类是否能直接访问父类的私有成员
#include <iostream>
#include <string>

using namespace std;

class Parent
{
private:
	int mv;
public:
	Parent()
	{
		mv = 1000;
	}
	int value()
	{
		return mv;
	}
};

class Child : public Parent
{
public:
	void addValue(int v)
	{
		mv = mv + v;//??????如何访问父类中非公有成员
	}
};


int main()
{   

    return 0;
}

关键字protected

  • 修饰的成员不能被外界直接访问
  • 但修饰的成员可以被子类直接访问
#include <iostream>
#include <string>

using namespace std;

class Parent
{
protected:
	int mv;
public:
	Parent()
	{
		mv = 1000;
	}
	int value()
	{
		return mv;
	}
};

class Child : public Parent
{
public:
	void addValue(int v)
	{
		mv = mv + v;//??????如何访问父类中非公有成员
	}
};


int main()
{   
	Parent p;
	
	cout << "p.value()" << p.value() << endl;
	
	//p.mv = 1000;
	
	Child c;
	
	cout << "c.value()" << c.value() << endl;
	
	c.addValue(100);
	
	cout << "c.value()" << c.value() << endl;
	
	//c.mv = 1000;
	
    return 0;
}

类和组合的示例

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

class Object
{
protected:	
	string mName;
	string mInfo;
public:
	Object()
	{
		mName = "obj";
		mInfo = "";
	}
	string name()
	{
		return mName;
	}
	string info()
	{
		return mInfo;
	}
	
};

class Point : public Object
{
private:
	int mX;
	int mY;
public:
	Point(int x = 0, int y = 0)
	{
		ostringstream s;
		
		mX = x;
		mY = y;
		mName = "Point";
		
		s << "p(" << mX << "." << mY << ")";
		
		mInfo = s.str();
		
	}
};

class Line : public Object
{
private:
	Point mP1;
	Point mP2;
public:
	Line(Point p1, Point p2)
	{
		ostringstream s;
		
		mP1 = p1;
		mP2 = p2;
		mName = "Line";
		
		s << "Line from " << mP1.info() << "to" << mP2.info() << endl;
		
		mInfo = s.str();
	}
};

int main()
{   
	Object o;
	Point p(1, 2);
	Point pn(5, 6);
	Line l(p, pn);
	
	
	cout << o.name() << endl;
	cout << o.info() << endl;
	
	cout << endl;
	
	cout << p.name() << endl;
	cout << p.info() << endl;
	
    return 0;
}

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页