信管14:基类和派生类关系示例代码
2015-05-07 10:27
204 查看
/* 基类和派生类关系示例,
回答关联问题:
面向对象有哪几个基本特征?前面几章,我们讨论了其中哪几个特征?并解释。
掌握以下知识点:
1.掌握什么是多态?
2.多态分类:编译时多态和运行时多态。在C++中,二者是通过什么来实现的?
*/
/* 本例讲基类与派生类对象间兼容关系 */
#include<iostream>
using namespace std;
/*-------声明基类Base--------- */
class Base{
public:
int i;
Base(int x){ i=x; }
void show()
{ cout<<" Base "<<i<<endl; }
};
/*-----声明公有派生类Derived-----*/
class Derived:public Base{
public:
int y;
Derived(int x,int y1):Base(x){y=y1; }
void show()
{ cout<<" Base, i="<<i<<" derive, y="<<y<<endl; }
};
/*----普通函数,形参为基类对象的引用---*/
void fun(Base &bb)
{ cout<<" i= "<<bb.i<<endl; }
/*-----主函数----*/
int main()
{ Base b1(100);
Derived d1(11,1),d2(22,2),d3(33,3),d4(44,4);
cout<<" 1:********************"<<endl;
b1.show();
cout<<" 2:********************"<<endl;
d1.show();
d1.Derived::show();
d1.Base::show();
cout<<" 3:********************"<<endl;
b1=d1;
b1.show();
Base &b2=d2;
b2.show();
cout<<" 4:********************"<<endl;
Base *bp=&b1;
bp->show();
bp=&d1; //基类指针可以指向公有派生类对象
bp->show();
d1.show();
// bp->Derived::show(); //错误,基类指针可以指向公有派生类对象,但能能访问从基类来的成员成员
cout<<" 5:********************"<<endl;
fun(d4);
// Derived *p2=&b1; //错误,派生类指针不能指向基类对象
system("pause");
return 0;
}
回答关联问题:
面向对象有哪几个基本特征?前面几章,我们讨论了其中哪几个特征?并解释。
掌握以下知识点:
1.掌握什么是多态?
2.多态分类:编译时多态和运行时多态。在C++中,二者是通过什么来实现的?
*/
/* 本例讲基类与派生类对象间兼容关系 */
#include<iostream>
using namespace std;
/*-------声明基类Base--------- */
class Base{
public:
int i;
Base(int x){ i=x; }
void show()
{ cout<<" Base "<<i<<endl; }
};
/*-----声明公有派生类Derived-----*/
class Derived:public Base{
public:
int y;
Derived(int x,int y1):Base(x){y=y1; }
void show()
{ cout<<" Base, i="<<i<<" derive, y="<<y<<endl; }
};
/*----普通函数,形参为基类对象的引用---*/
void fun(Base &bb)
{ cout<<" i= "<<bb.i<<endl; }
/*-----主函数----*/
int main()
{ Base b1(100);
Derived d1(11,1),d2(22,2),d3(33,3),d4(44,4);
cout<<" 1:********************"<<endl;
b1.show();
cout<<" 2:********************"<<endl;
d1.show();
d1.Derived::show();
d1.Base::show();
cout<<" 3:********************"<<endl;
b1=d1;
b1.show();
Base &b2=d2;
b2.show();
cout<<" 4:********************"<<endl;
Base *bp=&b1;
bp->show();
bp=&d1; //基类指针可以指向公有派生类对象
bp->show();
d1.show();
// bp->Derived::show(); //错误,基类指针可以指向公有派生类对象,但能能访问从基类来的成员成员
cout<<" 5:********************"<<endl;
fun(d4);
// Derived *p2=&b1; //错误,派生类指针不能指向基类对象
system("pause");
return 0;
}
相关文章推荐
- 信管14:多重继承-虚基类示例代码?
- 信管14:虚函数示例代码一
- 信管14:前四章节课堂小测-编程示例代码
- 基类中this指针和派生类对象的关系,同名隐藏原则和作用域的示例
- 信管14:虚函数示例代码二
- 信管14:纯虚函数示例代码
- 信管14:类的继承示例代码2
- 信管14:多重继承二义性示例代码
- 基类和派生类之间的关系
- ArrayList 与 List 关系与代码示例 - Java
- 信管14:静态数据成员示例
- uml类关系图示及示例代码
- 基类与派生类对象的关系
- 关于C++中,基类 派生类的关系 重载 覆盖 面对对象开发的必须要理解的非常好
- c++派生类转换为基类与public、protected、private继承的关系
- 派生类和基类的关系
- Hibernate多对一关系代码示例(Many-To-One)
- 信管14:对象的成员访问示例
- 一周最新示例代码回顾 (5/14–5/20)
- 基类和派生类的关系以及调用范围