P129.CPP
#include <iostream.h>
#include <string.h>
class String
{
private:
char * str;
public:
String(char * s="") //单参数构造函数
{
cout << "在构造函数中/n";
int size = strlen(s);
str = new char[size+1];
strcpy(str,s);
}
String(String & ss) //复制构造函数
{
cout << "在复制构造函数中/n";
str = new char [strlen(ss.str)+1];
strcpy(str,ss.str);
}
~String()
{delete str;}
void showstring()
{cout << str << endl;}
};
void main()
{
String s1 = "内存中的字符串 ";
cout << "S1 = ";
s1.showstring();
String s2(s1);
cout << "s2 = ";
s2.showstring();
}
P131.CPP
#include <iostream.h>
#include <string.h>
class String
{
private:
char * str;
public:
String(char * s="")
{
cout << "在构造函数中/n";
int size = strlen(s);
str = new char[size+1];
strcpy(str,s);
}
~String()
{delete str;}
String& operator=(String& ss)
{
cout << "赋值操作符/n";
delete str;
str = new char [strlen(ss.str)+1];
strcpy(str,ss.str);
return *this;
}
void showstring()
{cout << str <<endl;}
};
void main()
{
String s1 = "内存中的字符串 ";
cout << "S1 = ";
s1.showstring();
String s2;
s2 = s1;
cout << "s2 = ";
s2.showstring();
}
p132.CPP
//从极坐标转移为直角坐标
#include <iostream.h>
#include <math.h> //包括sin(),cos()等等
class Polar //极坐标中的点
{
private:
double radius; //极径
double angle; //极角(弧度)
public:
Polar()
{
radius = 0.0;
angle = 0.0;
}
Polar(double r,double a)
{
radius = r;
angle = a;
}
void display()
{
cout << "(" << radius<< "," <<angle << ")";
}
double getr()
{
return radius;
}
double geta()
{
return angle;
}
};
class Rec
{
private:
double xco; //X坐标
double yco; //y坐标
public:
Rec()
{
xco = 0.0;
yco = 0.0;
}
Rec(double x,double y)
{
xco=x;
yco=y;
}
Rec(Polar p)
{ //极坐标到直角坐标
float r = (float)p.getr();//从Polar对象中获得极径和极角
float a = (float)p.geta();
xco = r * cos(a); //变成x坐标和y坐标
yco = r * sin(a);
}
void display()
{
cout << "(" << xco << ", " <<yco << ")";
}
};
void main()
{
Rec rec;
Polar pol(10.0, 0.785398);
rec = pol; //使用转换函数(或rec = Rec(pol);)
cout << "/nPol=";
pol.display(); //显示原始极坐标
cout<< "/nRec=";
rec.display(); //显示等价的直角坐标
}