c++基础回顾

c++继承方式

公有继承,父类的私有成员不可访问,通过父类的公有函数以及保护函数访问

私有继承,父类成员在派生类中为私有成员等。

初始化顺序先父类,再是派生类,析构刚好相反,

当用父类指针或者引用实现多态时,析构函数要声明成虚函数,不然只会调用父类的析构函数

#include <iostream>
using namespace std;
class base{
private :float x;
public :base(float a){
			cout<<"base init"<<endl;
		x=a;
	}
		virtual void fun(float a){
			cout<<"fun base"<<a<<endl;
		}

		void g(int a){
			cout<<"g  base"<<a<<endl;
		}
		~base(){
			cout<<"base detele "<<endl;
		}
};
class son :public base{
private : int s;
public :
	son(float a,int b):base(a),s(b){
		cout<<"son init"<<endl;
	}
	void fun(float a){
     cout<<"fun son"<<a<<endl;
	}
	void g(int a){
		cout<<"g  son"<<a<<endl;
	}
	~son(){
		cout<<"son delete"<<endl;
	}
};
int main(){
	float a=3.14;
	float b=2.56;
	int d=1;
	int c=8;
	base *p;
	son test1(a,d);
	base &p2= son(a,d);
	//delete p2;
	son *p1=&test1;
	p=&test1;
	p1->fun(b);
	p1->g(c);
	p->fun(b);
	p->g(a);
	p2.fun(b);
	p2.g(a);
//	getchar();
	return 0;

}


c++ 复数类以及operator 重载输入 加法,乘法

#include<iostream>
using namespace std;
class complax{
private: int real;
	 int image;
public :
	complax(){
		real=0;
		image=0;
	}
	complax(int r,int image){
		real=r;
		this->image=image;
	 }
	 void set_init(int r,int i){
		 real=r;
		 image=i;
	}
	void show(){
		cout<<real;
       if(image>=0)
		   cout<<"+"<<image<<"i"<<endl;
	   else
	   {
		   cout<<image<<"i"<<endl;

	   }
	}
	//重载+
	complax operator +(const complax &t){
		return complax(this->real+t.real,this->image+t.image);
	}
   //重载输入,只能是友元,为什么?因为cin对象为系统的对象没有this指针,不能通过对象来调用
	//只能重载为友元函数或者是类外的普通的函数
	friend istream &operator >>(istream &in,complax &a){
		int r,i;
		in>>r>>i;
		a.real=r;
		a.image=i;
		return in;
	}
	//(a+bi)(c+di)=(ac-bd)+(bc+ad)i
	friend complax operator*(const complax &a,const complax &b){
		int r;
		int i;
		r=a.real*b.real-a.image*b.image;
		i=a.image*b.real+a.real*b.image;
		return complax(r,i);
	}

};

void main(){
	complax a;
	complax b;
	a.show();
	cin>>a>>b;
	a.show();
	b.show();
	complax c=a+b;
	c.show();
	complax d=a*b;
	d.show();
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值