继承中的访问级别
#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;
Child c;
cout << "c.value()" << c.value() << endl;
c.addValue(100);
cout << "c.value()" << c.value() << endl;
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;
}