菜逼的我刚接触面向对象编程,在摸索类的实现,然后我写了main.cpp, time.h, time.cpp三个文件来实现一个时间类。
但是编译报错,提示“[Error] no matching function for call to 'time::Set_Hour(int&)'。”
下面是我的源码:
这是第一段 main.cpp
#include "time.h"
#include <iostream>
using namespace std;
int main()
{
time a;
int b=8,c=9,d=8;
a.Set_Hour(b);
a.Set_Minute(c);
a.Set_Second(d);
a.Show_Time();
return 0;
}
这是第二段 time.h
#ifndef _time_H
#define _time_H
#include <iostream>
using namespace std;
class time
{
public:
void Set_Hour(int h);
void Set_Minute(int m);
void Set_Second(int s);
void Show_Time();
private:
int hour;
int second;
int minute;
};
#endif
这是第三段 time.cpp
#include"time.h"
#include<iostream>
using namespace std;
void time::Set_Hour(int h)
{
hour=h;
}
void time::Set_Minute(int m)
{
minute=m;
}
void time::Set_Second(int s)
{
second=s;
}
void time::Show_Time()
{
cout<<hour<<":"<<endl<<minute<<":"<<endl<<second;
}
你的各个函数写的没错,你先把它们写到一个文件里面,别搞出这么多文件来。反正在我上面运行的好好的
#include
using namespace std;
class time
{
public:
void Set_Hour(int h);
void Set_Minute(int m);
void Set_Second(int s);
void Show_Time();
private:
int hour;
int second;
int minute;
};
void time::Set_Hour(int h)
{
hour=h;
}
void time::Set_Minute(int m)
{
minute=m;
}
void time::Set_Second(int s)
{
second=s;
}
void time::Show_Time()
{
cout<<hour<<":"<<endl<<minute<<":"<<endl<<second;
}
int main(void)
{
time a;
int b=8,c=9,d=8;
a.Set_Hour(b);
a.Set_Minute(c);
a.Set_Second(d);
a.Show_Time();
return 0;
}
应该是没有初始化吧,你只是声明了对象a,改为 time a=new time() 试试?
楼主自己解决了,方法是在 time.h文件的class里加一句 time ( int ahour=0, int aminute=0, int asecond=0 );
然后在time.cpp文件里实现一个time::time ( int ahour, int aminute, asecond) : hour(ahour), minute(aminute), second(asecond) {} 的函数。