发布网友 发布时间:2023-11-18 22:15
共4个回答
热心网友 时间:2024-11-30 15:41
上机调试并改正下面的程序,分析原因,写出实验报告。
要求:将对象t1的三个成员变量hour, minute, second设置为10, 20, 30;通过指针变量p将将对象t2的三个成员变量hour, minute, second设置为11, 21, 31;通过引用变量t将将对象t3的三个成员变量hour, minute, second设置为12, 22, 32。
程序代码如下:
class Time
{
private:
int hour, minute, second;
public:
void SetTime()
{ hour = 10; minute = 20; second = 30; }
void SetTime(int h, int m, int s);
}
Time:: SetTime(int h, int m, int s)
{ hour = h; minute = m; second = s; }
void main()
{ Time t1, t2, t3, *p;
t1. hour = 10; t1. minute = 20; t1. second = 30;
p = t2;
p-> hour = 11; p-> minute = 21; p-> second = 31;
Time &t;
t = t3;
t.SetTime(12, 22, 32);
}
1.error C2628: 'Time' followed by 'void' is illegal (did you forget a ';'?)
c++不同于java,在定义类的时候在}后面一定要加上一个;以表示类得结束
2.error C2248: 'hour' : cannot access private member declared in class 'Time'
不能访问类内的私有成员,在这里我改变了成员变量的访问权限,改为public类型的
private:
int hour, minute, second;
->
public:
int hour, minute, second;
3.为了测试是否改变了相应的数值,在这里我加入了输入输出流操作
#include<iostream>
using namespace std;
并且定义的输出函数
void PrintElem()
{
cout<<"hour="<<hour<<endl;
cout<<"minute="<<minute<<endl;
cout<<"second="<<second<<endl;
}
同时把下面的操作事先注释掉,一面影响之前的调试
4. #include<iostream>
using namespace std;
class Time
{
public:
int hour, minute, second;
public:
// void SetTime()
// { hour = 10; minute = 20; second = 30; }
void SetTime(int h, int m, int s);
void PrintElem()
{
cout<<"hour="<<hour<<endl;
cout<<"minute="<<minute<<endl;
cout<<"second="<<second<<endl;
}
};
void Time::SetTime(int h, int m, int s)
{
hour = h;
minute = m;
second = s;
}
void main()
{
Time t1;
t1. hour = 10; t1. minute = 20; t1. second = 30;
t1.PrintElem();
//p = t2;
//p-> hour = 11; p-> minute = 21; p-> second = 31;
//Time &t;
//t = t3;
//t.SetTime(12, 22, 32);
}
这样实现了第一个问题
5. error C2679: binary '=' : no operator defined which takes a right-hand operand of type 'class Time' (or there is no acceptable conversion)
不能直接把一个类的对象放入指针,但是可以传一个引用过去
p = &t2;
这样是把这个对象的地址放入了指针,然后对成员变量进行访问
6. error C2530: 't' : references must be initialized
在定义地址指向的时候要让他指向一个变量或者类的对象
Time &t = t3;
这样以后就可以实现了
下面是改好的正确的例子
#include<iostream>
using namespace std;
class Time
{
public://改变成员变量的访问类型
int hour, minute, second;
public:
void SetTime()
{ hour = 10; minute = 20; second = 30; }
void SetTime(int h, int m, int s);
void PrintElem()
{
cout<<"hour="<<hour<<endl;
cout<<"minute="<<minute<<endl;
cout<<"second="<<second<<endl;
}
};
void Time::SetTime(int h, int m, int s)
{
hour = h;
minute = m;
second = s;
}
void main()
{
Time t1,t2,t3,*p;
t1. hour = 10; t1. minute = 20; t1. second = 30;
t1.PrintElem();
p = &t2; //用p指向t2的地址
p-> hour = 11; p-> minute = 21; p-> second = 31;
t2.PrintElem();
Time &t = t3;
t.SetTime(12, 22, 32);
t3.PrintElem();
}
输出结果为:
热心网友 时间:2024-11-30 15:42
那个*p不能用 类的private成员 不能你这么初始化的热心网友 时间:2024-11-30 15:42
#include <iostream>热心网友 时间:2024-11-30 15:43
class Time