C++ 面向对象- -一些简单练习(三)

目录

1、类的简单创建

2、类对象转化为类型数据

3、友元类

4、普通函数作为友元函数

5、成员函数作为友元函数

6、有关类的类型转换

7、基类与派生类的转换

8、类的调用(引用)

9、setw的使用(控制输出占用的列数)

10、数组求最值(类)

11、对象数组

12、函数的重载


 

1、类的简单创建

#include <iostream>
using namespace std;
class Student {
	int num ;
	string name ;
	string sex ;
	public :
		void display_1(){
			cin>>num>>name ;
			cin >> sex ;
			cout << "num=" << num <<endl;
			cout << "sex=" << sex << endl;
		}
		void display_2();
};
void Student :: display_2(){
//	cin>>sex ;
	cout << "name=" << name << endl;
} 
class Time{
	int hour ;
	int min ;
	int sec ;
	public :
		void display(Student s){
			cin >> hour >> min >> sec ;
			cout << "时间:" << hour << ":" << min << ":" << sec <<endl;
			s.display_2();
		}
}; 
int main()
{
	Student s ;
	Time t ;
	s.display_1();
	s.display_2();
	cout << endl;
	
	t.display(s);
	
	return 0;
 } 

 

2、类对象转化为类型数据

#include <iostream>
using namespace std;
class Complex {
		double real;
		double imag;
	public:
		Complex(double r,double i) ;
		Complex(double r=0){
			real=r ;
			imag=0 ;
		}
		Complex operator+(Complex& c){  
			return Complex(real+c.real,imag+c.imag) ;
		} 
//		Complex operator+(int i){
//			return Complex(real+i,imag) ;
//		} 实现的结果和上边一样。因为转换构造函数 
		operator int(){
			return real ;
		}	
		void show(){
			cout << "(" << real << "+" <<imag << "i)" <<endl; 
		}
};
Complex::Complex(double r,double i){
	real = r ;
	imag = i ;
}
int main(){
	Complex c1(1,1) , c2(2) ,c3(3) ;
	int j=1 ,i=1 ;
	cout << "c1= 	";c1.show();
	cout << "c2=	";c2.show();
	cout << "j=		";
	j=c3+i;cout << j <<endl;
	cout << "c3=	";c3.show();
	cout << "c3+j=	";
	c2=c3+j;c2.show(); 
	//由于有转换构造函数,相当于执行:c2=c3+Complex(j)  
	cout << "i=		";
	i=c1+c2 ;cout << i << endl; 
}

 

3、友元类

#include <iostream>
using namespace std ;
class Date;
class Time{
		int hour ;
	public:
		Time(int h=0):hour(h){}
		void display(){
			cin >> hour ;
			cout << hour<< endl;
		}
		friend Date;			//声明友元类!! 
};
class Date{
	public:
		void display_1(Time &);			//注意同样需要实参的传入 
};
void Date::display_1(Time &t){
	cout <<"友元类访问数据成员:" <<t.hour << endl;
	cout << "友元类调用成员函数:" << endl;
	t.display();
}
int main()
{
	Time t;
	t.display();
	Date d;
	d.display_1(t);			//一个类的对象作为另一个类的实参传入. 
  }  

 

4、普通函数作为友元函数


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值