案例一:
class A {
int x, y;
public:
int getx() {
return x;
}
protected:
int gety() {
return y;
}
};
class B : private A /* public A */ /* protected A */{
bool visible;
public:
using A::getx;
A::gety; // deprecated
};
案例二:
class MyList {
struct Node
{
int v;
Node* next;
Node(int v, Node* n) {
this->v = v;
next = n;
}
~Node() {
cout << "~Node()\n";
delete next;
next = nullptr;
}
} *head;
public:
MyList() {
head = nullptr;
}
~MyList() {
if (head != nullptr) {
delete head;
head = nullptr;
}
}
int insert(int v) {
head = new Node(v, head);
if(head) return 1;
return 0;
}
int contain(int v) {
// 这里要注意,使用局部变量
// 不要使用 head,会改变整个链表的头指针
Node* tmp = head;
while (tmp != nullptr)
{
if (tmp->v == v) return 1;
tmp = tmp->next;
}
return 0;
}
};
class MySet : protected MyList {
int count;
public:
MySet() { count = 0; };
using MyList::contain;
int insert(int v) {
if (!contain(v) && MyList::insert(v)) return ++count;
return 0;
}
};
int main()
{
MySet l;
l.insert(1);
l.insert(2);
l.insert(3);
cout << l.insert(4) << endl;
cout << l.contain(3) << endl;
//MyList& list = l; // 不允许对不可访问的基类 "MyList" 进行转换
return 0;
}