您的位置:首页 > 编程语言 > C语言/C++

C++继承问题(白兰花例)

2016-04-11 12:46 453 查看
C++中有三种类的访问限定符,同样在运用继承这个知识的时候,也有三种继承方式,public,private,protected:

如图:



1.公有继承

这种情况下,基类成员的公有成员和保护成员在被派生类继承的时候,他们的性质不变,可被派生类对象访问,但是私有成员,不可被访问。

2.私有继承

基类成员都不可被派生类对象访问。

3.保护继承

基类的公有成员函数和保护成员函数在派生类中都是保护成员函数,只能被派生类的成员函数或者由友员访问。



代码:例子:

#include <iostream>
#include <string>
using namespace std;

class Botany
{

public://构造函数(Botany)

Botany(char* name = "")

:_name(name)
{
cout << "Botany()" << endl;
}

Botany(const Botany& s)
:_name(s._name)
{
//cout << "Botany(const Botany& s)" << endl;
}

Botany& operator=(const Botany& s)
{
if (this != &s)
{
_name = s._name;
}
return *this;
}
~Botany()
{

}

virtual void Display()
{
cout << "Botany::" << _name << endl;
}

protected:
string _name;
};

class Tree :virtual public Botany     //
{
public:
Tree(char* name, int hight = 0)
:Botany(name)             //继承基类时 写法
, _hight(hight)

{
//cout << "Tree()" << endl;//测试需要
}

Tree(const Tree& s)
: Botany(s)
, _hight(s._hight)

{
//cout << "Tree(const Tree& s)" << endl;
}

Tree& operator=(const Tree& s)
{
if (this != &s)
{
Botany::operator=(s);
_hight = s._hight;
}
return *this;
}
~Tree()
{
}

void Display()
{
cout << "Tree::" << _hight << endl;
}
protected:
int _hight;
};

//FLOWER
class Flower :virtual public Botany
{
public:

Flower(char * name, int colour)
: Botany(name)
, _colour(colour)

{
//cout << "Flower()" << endl;
}
Flower(const Flower& s)
: Botany(s)
, _colour(s._colour)
{
//cout << "Flower(const Flower& s)" << endl;
}

Flower& operator=(const Flower& s)
{
if (this != &s)
{
Botany::operator=(s);
_colour = s._colour;
}
return *this;
}
~Flower()
{
}
void Display()
{
cout << "Flower::" << _colour << endl;
}
protected:
int _colour;
};

// 白兰花,即是树又是花。
class MicheliaAlba : public Flower, public Tree
{
public:
MicheliaAlba(char* name, int hight, int colour)
:Botany(name)
, Flower(name, colour)
, Tree(name, hight)
{
}

MicheliaAlba(const MicheliaAlba& s)
: Botany(s)
, Flower(s)
, Tree(s)
{}

MicheliaAlba& operator=(const MicheliaAlba& s)
{
if (this != &s)
{
Botany::operator=(s);
Flower::operator=(s);
Tree::operator=(s);
}
return *this;
}

~MicheliaAlba()
{}

void Display()
{
cout << " MicheliaAlba::" << _name << "-" << _colour << "-" << _hight << endl;
}
};

void Test1()
{
Botany l1("兰花");
Flower l2("兰花", 1);
Tree l3("兰花", 2);
//Botany *p1 = &l1;
//Botany& p2 = l2;//虚函数 代表测试
//Botany *p2 = &l3;
l1.Display();
l2.Display();
MicheliaAlba s1("兰花", 1, 10);
s1.Display();

}
int main()
{
Test1();
getchar();
return 0;
}


基类成员
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: