注册 登录
编程论坛 C++教室

如何改写这个C++程序?

淡蓝色的猪 发布于 2012-10-04 01:24, 575 次点击
有以下程序:
#include <iostream>
using namespace std;
class Time
{public:
int hour;
int minute;
int sec;
};
int main()
{Time t1;
cin>>t1.hour;
cin>>t1.minute;
cin>>t1.sec;
cout<<t1.hour<<":"<<t1.minute<<":"<<t1.sec<<endl;
return 0;
}

改写要求:
1.将数据成员改为私有的;
2.将输入和输出功能改为成员函数实现;
3.在类体内定义成员函数。

   求大神..真心求教.

下面是我改写的.不知道对不对..

#include<iostream>
using namespace std;
class Time
{public:
  void set_Time();
  void show_Time();
 private:
int hour;
int minute;
int sec;
};
int main()
{Time t1;
t1.set_Time();
t1.show_Time();
return 0;
};
void Time::set_Time()
{cin>>hour;
cin>>minute;
cin>>sec;
}
void Time::show_Time()
{cout<<hour<<":"<<minute<<":"<<sec<<endl;
}


[ 本帖最后由 淡蓝色的猪 于 2012-10-4 01:50 编辑 ]
3 回复
#2
qunxingw2012-10-04 10:41
3.在类体内定义成员函数。
#include<iostream>
using namespace std;
class Time
{
  //void set_Time();
 // void show_Time();
private:
int hour;
int minute;
int sec;

public:
  set_Time()
  {
     cin>>hour;
     cin>>minute;
     cin>>sec;
  }
show_Time()
 {
     cout<<hour<<":"<<minute<<":"<<sec<<endl;
 }
};
int main()
{Time t1;
t1.set_Time();
t1.show_Time();
return 0;
}
#3
w8233524172012-10-04 15:59
你的程序运行时没有什么问题的,但是违背你的第三个条件,没有在类体内定义成员函数,你只做了声明。楼上正解
#4
山科大梦2012-10-05 21:23
#include <iostream>
using namespace std;
class Time
{private:
int hour;
int minute;
int sec;
public:
void set()
{
    cin>>hour>>minute>>sec;
}
void show()
{
    cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
};
int main()
{Time t1;
t1.set();
t1.show();
return 0;
}
1