这个C++程序为什么不能这样写?

来源:百度知道 编辑:UC知道 时间:2024/05/29 05:42:42
#include <iostream>
using namespace std;
class Clock
{
private:
int hour;
int minute;
int second;
public:
Clock(int h,int m,int s)
{
hour=h;
minute=m;
second=s;
}
void display()
{
cout<<hour<<":"<<minute<<":"<<second<<endl;
}
};
main()
{
int h,m,s;
cin>>h>>m>>s;
Clock clo(h,m,s);
clo.display();
return 0;
}
为什么main函数内这样写错误?
main()
{
Clock clo;
int h,m,s;
cin>>h>>m>>s;
clo(h,m,s);
clo.display();
return 0;
}

构造函数在定义一个对象的时候调用,即只在对象建立的时候调用一次。

#include <iostream>
using namespace std;
class Clock
{
private:
int hour;
int minute;
int second;
public:
Clock clo();//必须加上。
Clock(int h,int m,int s)
{
hour=h;
minute=m;
second=s;
}
void display()
{
cout<<hour<<":"<<minute<<":"<<second<<endl;
}
};
/*main()
{
int h,m,s;
cin>>h>>m>>s;
Clock clo(h,m,s);
clo.display();
return 0;
}
为什么main函数内这样写错误?*/
main()
{
Clock clo; //它前没有可调用的结构函数。
int h,m,s;
cin>>h>>m>>s;
clo(h,m,s);
clo.display();
return 0;
}

main()
{
Clock clo;
int h,m,s;
cin>>h>>m>>s;
clo(h,m,s);构造函数在声明的时候调用,之后不能在这样调用
clo.display();
return 0;
}

m