1.检查错误。
代码:
#include <iostream>
using namespace std;
class Time
{
private:
/* data */
public:
Time(/* args */);
~Time();
void set_time(void);
void show_time(void);
int hour;
int minute;
int sec;
};
Time::Time(/* args */)
{
}
Time::~Time()
{
}
Time t;
int main() {
t.set_time();//成员函数,需要通过对象来调用
t.show_time();
return 0;
}
void Time::set_time(void) {//成员函数,定义的时候需要添加类名来说明
cin >>t.hour;
cin >>t.minute;
cin >>t.sec;
}
void Time::show_time(void) {
cout <<t.hour <<":" <<t.minute <<":" <<t.sec <<endl;
}
输出结果:
2.成员函数的私有化,定义成员函数。
代码:
#include <iostream>
using namespace std;
class Time
{
private:
int hour;
int minute;
int sec;
public:
Time(/* args */);
~Time();
void set_time(void) {
cin >>hour;
cin >>minute;
cin >>sec;
}
void show_time(void) {
cout <<hour <<":" <<minute <<":" <<sec <<endl;
}
};
Time::Time(/* args */)
{
}
Time::~Time()
{
}
Time t;
int main() {
t.set_time();
t.show_time();
return 0;
}
输出结果:
3.类内声明,类外实现成员函数。
代码:
9_3.cpp
#include "Student.h"
int main() {
Student stu;
stu.set_value();
stu.display();
return 0;
}
student.cpp
#include <string>
#include <iostream>
using namespace std;
class Student
{
private:
int num;
string name;
char sex;
public:
void display();
void set_value();
};
inline void Student::display() {
cout << "num = " << num << endl;
cout << "name = " << name << endl;
cout << "sex = " << sex << endl;
}
void Student::set_value() {
cin >> num;
cin >> name;
cin >> sex;
}
输出结果:
4成员函数的声明和实现分离
代码:
9_4.cpp
#include "Student.h"
int main() {
Student stu;
stu.set_value();
stu.display();
hello();
return 0;
}
Student.cpp
#include "Student.h"//<>is not fit
void Student::display() {
cout << "num = " << num << endl;
cout << "name = " << name << endl;
cout << "sex = " << sex << endl;
}
void Student::set_value() {
cin >> num;
cin >> name;
cin >> sex;
}
void hello() {
cout <<"Hello world1" <<endl;
}
Student.h
#include <string>
#include <iostream>
using namespace std;
class Student
{
private:
int num;
string name;
char sex;
public:
void display();
void set_value();
};
输出结果:
6.计算长方体体积
代码:
#include <iostream>
using namespace std;
class Cube
{
private:
int length;
int width;
int height;
public:
Cube(int l, int w, int h);
~Cube();
int volume();
};
Cube::Cube(int l, int w, int h)
{
length = l;
width = w;
height = h;
}
Cube::~Cube()
{
}
int main() {
int a,b,c;
cin >> a >> b >> c;
Cube c1(a, b, c);
cout << "volume = " <<c1.volume() <<endl;
cin >> a >> b >> c;
Cube c2(a, b, c);
cout << "volume = " <<c2.volume() <<endl;
cin >> a >> b >> c;
Cube c3(a, b, c);
cout << "volume = " <<c3.volume() <<endl;
}
int Cube::volume() {
return height*width*length;
}
输出结果: