实验内容:
1、分析下面的程序,回答问题。
#include
using namespace std;
class CPoint
{
public:
void Set(int x,int y);
void Print();
private:
int x;
int y;
};
void CPoint::Set(int x,int y)
{
This->x = x;
This->y = y;
}
void CPoint::Print()
{
cout<<"x="<<x<<",y="<<y<<endl;
}
void main()
{
CPoint pt;
pt.Set(10,20);
pt.Print();
}
问题一:以上程序编译能通过吗,试解释该程序?
问题二:以上程序的运行结构是否正确,如果不正确,试分析为什么,应该如何改正?
2、阅读程序回答问题。
#include
using namespace std;
class CPerson
{
public:
void Print();
private:
CPerson();
private:
int age;
char *name;
};
CPerson::CPerson()
{}
void CPerson::Print()
{
cout<<"name="<<name<<",age="<<age<<endl;
}
void main()
{
CPerson ps(23,"张三");
ps.Print();
}
问题一:以上程序存在三处大错误,在不改变主函数内容的前提下,试改正该
程序。
3、类 Person 的定义如下,请实现该类,并在主函数中创建对象 obj,然后使用
构造函数为 obj 赋予初始值(内容自定)。
class Person
{
public:
Person(char *xname,int xage,int xsalary,char *xtel);
void disp();
private:
char name[10];
int age;
int salary;
char tel[8];
};
4、分析并比较下列程序运行的结果。
程序一:
#include<iostream.h>
using namespace std;
class smallone
{
public:
smallone(int sma)
{ x=sma;
cout<<"sm constr:"<<sma<<"\n";
}
int getX()
{
return x;
}
~smallone()
{
cout<<"调用了析构函数释放对象!\n";
}
private :
int x;
};
void fn(int n)
{ smallone sm(n);
cout<<"in function fn with n="<<n<<" sm.x="<<sm.getX()<<endl;
}
int main()
{ fn(10);
fn(20);
return 0;
}
程序二:
#include<iostream.h>
using namespace std;
class smallone
{
public:
smallone(int sma)
{ x=sma;
cout<<"sm constr:"<<sma<<"\n";
}
int getX()
{
return x;
}
~smallone()
{
cout<<"调用了析构函数释放对象!\n";
}
private :
int x;
};
void fn(int n)
{ static smallone sm(n);
cout<<"in function fn with n="<<n<<" sm.x="<<sm.getX()<<endl;
}
int main()
{ fn(10);
fn(20);
return 0;
}
5、建立一个对象数组,内放 5 个学生的数据(学号、成绩),定义一个函数 max,用指向
对象的指针作函数参数,在 max 函数中找出 5 个学生中成绩最高者,并输出其学号。其中
将 max 函数作为类的友元函数。
第一个: include 是加载.h文件到cpp文件中 相当于直接复制过来, using namesoace 是使用命名空间 是直接在cpp文件中写入的,创建一个命名空间,对某些重复命名进行区分开来 ; 运行结构是正确的