C++基础知识实例
在考研复试复习C++的过程中(虽然我基本上忘光了),使用了清华大学出版社郑莉的教材,下面这个例子综合运用了前四章全部的知识,算是对基础知识的巩固吧。例子很简单,就是一个点类一个线段类,线段类含有两个点类的对象,和一个长度值。
还是直接上代码吧
#include <iostream>
#include <cmath>
using namespace std;
class line;
class Point
{
public:
Point(float x1=0,float y1=0);
Point(Point &P);
~Point()
{
cout << "Point类析构函数被调用" <<endl;
};
void Set_point(float x2,float y2);
void Set_point(line line1);
float Get_x()
{
return x;
};
float Get_y()
{
return y;
};
private:
float x;
float y;
};
class line
{
public:
line(Point P11,Point P22);
line(line &line);
~line()
{
cout << "line类的析构函数被调用" << endl;
}
float Get_len(){return len;}
void Get_P(void)
{
cout<< "(" <<P1.Get_x() <<","<<P1.Get_y() <<") " ;
cout<< "(" <<P2.Get_x() <<","<<P2.Get_y() <<")" <<endl;
}
Point Get_P2(void);
private:
Point P1,P2;
float len;
};
Point::Point(float x1,float y1)
{
x=x1;
y=y1;
cout << "Point类构造函数被调用" << endl;
}
Point::Point(Point &P)
{
x = P.x;
y = P.y;
cout << "Point类拷贝构造函数被调用" <<endl;
}
inline void Point::Set_point(float x2,float y2)
{
x=x2;
y=y2;
};
/*void Point::Set_point(line line1)
{
x = line1.Get_P2().Get_x();
y = line1.Get_P2().Get_y();
cout << endl <<"Point类使用line类的对象" <<endl;
}*/
inline void Point::Set_point(line line1)
{
x = line1.Get_P2().Get_x();
y = line1.Get_P2().Get_y();
cout << endl <<"Point类使用line类的对象" <<endl;
}
line::line(Point P11,Point P22):P1(P11),P2(P22)//参数表如常,只需要指明内嵌对象即可,这里要注意两次传递
{
cout << "line类的构造函数被调用" <<endl;
float len1 = P2.Get_x()-P1.Get_x();
float len2 = P2.Get_y()-P1.Get_y(); //说明即使是内嵌对象,不同类之间也不可以直接使用
len = sqrt(len1*len1 + len2*len2);
cout << "len=" <<len <<endl;
};
line::line(line &line)
{
P1=line.P1;
P2=line.P2;
len = line.len;
cout << "line类的拷贝构造函数被调用"<<endl;
}
Point line::Get_P2(void)
{
return P2;
}
int main()
{
Point P1,P2(1.0,2.0);
cout << "P1的坐标为:("<<P1.Get_x()<<","<<P1.Get_y()<<")"<<endl;
cout << "P2的坐标为:("<<P2.Get_x()<<","<<P2.Get_y()<<")"<<endl;
Point P3(P1);//这里是引用,所以拷贝构造函数被调用一次
cout << "P3的坐标为:("<<P3.Get_x()<<","<<P3.Get_y()<<")"<<endl;
line line1(P1,P2);
cout << "line1的长度为:" <<line1.Get_len()<<endl;
line line2(line1);
cout << "line2的长度为:" <<line1.Get_len()<<endl;
cout << "line2的坐标为:";
line2.Get_P();
cout <<endl;
Point P4;
P4.Set_point(line2);
cout << "P4的坐标为:("<<P4.Get_x()<<","<<P4.Get_y()<<")"<<endl;
cout <<endl;
return 0;
}
//我是真牛逼啊!