实验6_虚基类和运算符重载.doc

  1. 1、本文档共3页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
实验6_虚基类和运算符重载

实验6_虚基类和运算符重载 实验目的: 1. 掌握虚基类的定义和使用 2. 掌握运算符重载的定义和使用实验内容: 一、编辑、编译和运行程序: 1. 虚基类的使用[例Ex_VirtualBase] #includeiostream.h class A { public: int x; A(int a=0){ x=a;} }; class B1 : virtual public A // 公有继承虚基类 { public: int y1; B1(int a=0,int b=0):A(b){y1=a;} void print(void){ coutB1:x=x,y1=y1endl;} }; class B2 : virtual public A // 公有继承虚基类 { public: int y2; B2(int a=0,int b=0):A(b){y2=a;} void print(void){ coutB2:x=x,y2=y2endl;} }; class C : public B1,public B2 { public: int z; C(int a,int b,int d,int e,int m):B1(a,b),B2(d,e),A(){z=m;} /*从虚基类间接继承的派生类构造函数成员初始化列表中须列出虚基类构造函数,无参时可以省略。*/ void print(){ B1:: print();B2:: print(); coutz=zendl;} }; void main() { C c1(100,200,300,400,500); /* 调用 C(100,200,300,400,500): ①先调用A()结果:x=0 派生类对象构造函数执行虚基类构造函数。 ②再根据派生类定义时继承基类的列表从左向右顺序调用各个基类的构造函数, 调用B1(100,200)结果:y1=100 不执行虚基类构造函数。 调用B2(300,400)结果:y2=300 不执行虚基类构造函数。 ③最后执行C函数体中的内容: z=500c1.print(); // 输出 : c1.x=400; c1.print(); // 输出 : } . 运算符重载为类的成员函数。 #includeiostream.h class complex { public: complex(){real=imag=0;} complex(double r,double i){real=r;imag=i;} complex operator+(complex c) // 重载+,实现复数类对象加法运算 { complex temp; temp.real=real+c.real; temp.imag=imag+c.imag; return temp;} void print() { if(imag0)coutrealimagiendl; else coutreal+imagiendl; } private: double real,imag; }; void main() { complex c1(2.2,3.3),c2(4.4,-2.2),c3; c3=c1+c2; /* 当运算符的操作数是类的对象时, 为重载运算符,将调用运算符重载函数。 c1+c2:执行c1.operator+(c2) 左操作数调用运算符成员函数, 右操作数为实参。 = 默认行为是复制类对象的数据成员。 */ cout\nc1+c2=; c3.print(); } 3.运算符重载为类的友元函数 #includeiostream.h class complex { public: complex(){real=imag=0;} complex(double r,double i){real=r;imag=i;} friend complex operator+(complex c1, complex c2) // 重载+,实现类对象加法运算 { complex temp; temp.real=c1.real+c2.real; temp.imag=c1.imag+c2.imag; return temp; } void print() { if(imag0)coutrealimagiendl; else coutreal+imagiendl; } private: double real,imag; }; void main() { complex c1(2.2,3.3),c2(4.4,

文档评论(0)

xy88118 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档