第二章 类的对象和特性
1、改错,输出时间
#include <iostream>
#include<cstring>
using namespace std;
class Time{
private:
int hour;
int minute;
int sec;
public:
void set_time(){
cin>>hour>>minute>>sec;
};
void show_time(){
cout<<hour<<":"<<minute<<":"<<sec<<endl;
};
};
Time t;
int main() {
t.set_time();
t.show_time();
return 0;
}
2、改写例2.1
#include <iostream>
using namespace std;
class Time {
private:
int hour;
int minute;
int sec;
public:
void setTime() {
cin >> hour;
cin >> minute;
cin >> sec;
};
void showTime() {
cout << hour << ":" << minute << ":" << sec << endl;
};
};
int main() {
Time t;
cout << "请按小时:分钟:秒输入\n";
t.setTime();
t.showTime();
return 0;
}
3、修改第二题
#include <iostream>
using namespace std;
class Time {
private:
int hour;
int minute;
int sec;
public:
void setTime(void) ;
void showTime(void ) ;
};
void Time::setTime(void ) {
cin >> hour;
cin >> minute;
cin >> sec;
}
void Time::showTime(void ) {
cout << hour << ":" << minute << ":" << sec << endl;
}
int main() {
Time t;
cout << "请按小时:分钟:秒输入\n";
t.setTime();
t.showTime();
return 0;
}
4、
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
void display();
void set_value();
private:
int num;
string name;
char sex;
};
void Student::set_value()
{
cout<<"Please enter student num, name, sez: ";
cin>>num>>name>>sex;
}
void Student::display()
{
cout<<"num: "<<num<<endl;
cout<<"name: "<<name<<endl;
cout<<"sex: "<<sex<<endl;
}
int main()
{
Student stu;
stu.set_value();
stu.display();
system("pause");
return 0;
}
5、
//头文件:
class Arraymax
{
public:
void set_value();
void max_value();
void show_value();
private:
int array[10];
int max;
};
//源文件:
#include<iostream>
using namespace std;
void Arraymax::set_value()
{
int i;
for(i=0;i<10;i++)
cin>>array[i];
}
void Arraymax::max_value()
{
int i;
max=array[0];
for(i=0;i<10;i++)
if(array[i]>max)
max=array[i];
}
void Arraymax::show_value()
{
cout<<"max="<<max;
}
//主函数:
#include<iostream>
using namespace std;
int main()
{
Arraymax max1;
max1.set_value();
max1.max_value();
max1.show_value();
return 0;
}
6、编写对象求长方柱体积
#include <iostream>
using namespace std;
class TIJI {
private:
int length;
int width;
int height;
public:
void setV(void) ;
void getV(void ) ;
};
void TIJI::setV(void ) {
cin >> length;
cin >> width;
cin >> height;
}
void TIJI::getV(void ) {
int V=length*width*height;
cout<<"体积为:"<<V<<endl;
}
int main() {
TIJI t;
cout << "请按长、宽、高输入\n";
t.setV();
t.getV();
return 0;
}