关注公众号

关注公众号

手机扫码查看

手机查看

喜欢作者

打赏方式

微信支付微信支付
支付宝支付支付宝支付
×

C++之类的继承访问级别学习总结(三)

2020.9.29

4、定义类时访问级别的选择:

注解:从图中我们可以发现,当有发生继承关系时,就考虑使用protect关键字

5、组合和继承的综合运用

说明:Object这个类是被用来继承的;Line和Point两个类进行组合。

代码示例:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Object

protected:
   string mName;
   string mInfo;
public:
   Object()
   {
       mName = "Object";
       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();
   }
   int x()
   {
       return mX;
   }
   int y()
   {
       return mY;
   }
};
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();
       
       mInfo = s.str();
   }
   Point begin()
   {
       return mP1;
   }
   Point end()
   {
       return mP2;
   }
};
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;
   
   cout << endl;
   
   cout << l.name() << endl;
   cout << l.info() << endl;
   
   return 0;


推荐
热点排行
一周推荐
关闭