目录
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); //一个类的对象作为另一个类的实参传入.
}