这里简单给出多文件编程
1.函数的声明和实现:
声明放到头文件中,实现放到c.cpp中
类的声明和实现也是一样的。
为了防止重复,用两种方法,预处理和分离式编译.
#include <iostream>
#include "Clock.h"
using namespace std;
int main()
{
Clock c;
c.settime(23,8,20);
c.showtime();
return 0;
}
这里是main函数
下面是头文件:
#ifndef CLOCK_H
#define CLOCK_H
class Clock
{
public:
Clock();
~Clock();
Clock(const Clock& other);
void settime(int h,int m,int s);
void showtime();
private:
int m_hour;
int m_minute;
int m_second;
};
#endif // CLOCK_H
头文件只是作出声明。
下面是source文件:
#include "Clock.h"
#include <iostream>
#include <iomanip>
#include <cstdio>
using namespace std;
Clock::Clock()
{
this->m_hour=0;
this->m_minute=0;
this->m_second=0;
//ctor
cout<<"这个是函数的构造"<<endl;
}
Clock::~Clock()
{
cout<<"这是个函数的析构"<<endl;
}
void Clock::settime(int h,int m,int s)
{
if ((h>=0&&h<=23)&&(m>=0&&m<=59)&&(s>=0&&s<=59))
{
this->m_hour=h;
this->m_minute=m;
this->m_second=s;
}
}
void Clock::showtime()
{
printf("%02d:%02d:%02d\n",m_hour,m_minute,m_second);
}
Clock::Clock(const Clock& other)
{
//copy ctor
this->m_hour=other.m_hour;
this->m_minute=other.m_minute;
this->m_second=other.m_second;
}