实验目的和要求
1、熟悉类的定义格式和类中成员的访问权限。
2、构造函数与析构函数的调用时机与顺序。
3、掌握对象的定义以及对象的初始化的时机与方法。
实验内容
1、下面程序sy3_1.cpp中用ERROR标明的语句有错,在不删除和增加代码行的情况下,改正错误语句,使其正确运行。
-
//sy3_1.cpp
-
-
using namespace std;
-
class Aa
-
{
-
public:
-
Aa( int i= 0){a=i; cout<< "Constructor"<<a<< endl;}
-
~Aa(){ cout<< "Destructor"<<a<< endl;}
-
void print(){ cout<<a<< endl;}
-
private:
-
int a;
-
};
-
int main()
-
{
-
Aa a1(1),a2(2);
-
a1.print();
-
cout<<a2.a<< endl; //ERROR
-
return 0;
-
}
运行结果如下:
修改程序如下:
-
//sy3_1.cpp
-
-
using namespace std;
-
class Aa
-
{
-
public:
-
Aa( int i= 0){a=i; cout<< "Constructor"<<a<< endl;}
-
~Aa(){ cout<< "Destructor"<<a<< endl;}
-
void print(){ cout<<a<< endl;}
-
private:
-
int a;
-
};
-
int main()
-
{
-
Aa a1(1),a2(2);
-
a1.print();
-
a2.print();
-
return 0;
-
}
正确程序运行结果如下:
2、调试下列程序。
-
//sy3_2.cpp
-
-
using namespace std;
-
class TPoint
-
{
-
public:
-
TPoint( int x, int y){X=x,Y=y;}
-
TPoint(TPoint &p);
-
~TPoint(){ cout<< "Destructor is called\n";}
-
int getx(){ return X;}
-
int gety(){ return Y;}
-
private:
-
int X,Y;
-
};
-
TPoint::TPoint(TPoint &p)
-
{
-
X=p.X;
-
Y=p.Y;
-
cout<< "Copy-initialization Constructor is called\n";
-
}
-
int main()
-
{
-
TPoint p1(4,9);
-
TPoint p2(p1);
-
TPoint p3=p2;
-
TPoint p4,p5( 2);
-
cout<< "p3=("<<p3.getx()<< ","<<p3.gety()<< ")\n";
-
return 0;
-
}
在该程序中,将TPoint类的带有两个参数的构造函数进行修改,在函数体内增加下述语句:
cout<<"Constructor is called.\n";
(1)写出程序的输出结果,并解释输出结果。
修改程序如下:
-
//sy3_2.cpp
-
-
using namespace std;
-
class TPoint
-
{
-
public:
-
TPoint( int x, int y){X=x,Y=y;}
-
TPoint(TPoint &p);
-
~TPoint(){ cout<< "Destructor is called\n";}
-
int getx(){ return X;}
-
int gety(){ return Y;}
-
private:
-
int X,Y;
-
};
-
TPoint::TPoint(TPoint &p)
-
{
-
X=p.X;
-
Y=p.Y;
-
cout<< "Copy-initialization Constructor is called\n";
-
cout<< "Constructor is called\n";
-
}
-
int main()
-
{
-
TPoint p1(4,9);
-
TPoint p2(p1);
-
TPoint p3=p2;
-
cout<< "p3=("<<p3.getx()<< ","<<p3.gety()<< ")\n";
-
return 0;
-
}
原程序运行结果如下:
输出结果解释:
(2)按下列要求进行调试:
在主函数体内,添加下列说明语句:
TPoint P4,P5(2);
-
//sy3_2.cpp
-
-
using namespace std;
-
class