如果一个类包含另一个类的对象,是否可以通过在C++中包含类的构造函数中设置默认值来初始化它



编译此代码会产生错误

error time constructor time::time(int,int,char) cannot be overloaded with time::time(int,int,char)

我正在努力减少重载的构造函数,所以我正在努力在构造函数参数中给定默认值。entry类的构造函数中的行entry(int sno=5,time t{1,2,'p'});是否有效?如果一个类包含另一个类的复杂对象,那么它可以用这种方式初始化吗?

#include<iostream>
using namespace std;

class time
{
int hours;
int mins;
char ap;

public:
time(int hours=0,int mins=0,char ap='n');
time(int a, int b, char c): hours{a},mins{b},ap{c}
{
}

void showtime()
{
cout<<"nTime : "<<hours<<" "<<mins<<" "<<ap<<endl;
}
};
class entry{
int sno;
time t;
public:
entry(int sno=5,time t{1,2,'p'});
void showdata()
{
cout<<"ne : "<<sno<<" : ";
t.showtime();
}

};

int main()
{
entry e;
e.showdata();
return 0;
}

是的,这只是语法问题:

#include<iostream>
using namespace std;
class Time
{
int _hours;
int _mins;
char _ap;

public:
Time(int hours=0,int mins=0,char ap='n'): _hours(hours),_mins(mins),_ap(ap)
{};

void showtime()
{
cout<<"nTime : "<< _hours << " " << _mins << " " << _ap << endl;
}
};
class entry{
int _sno;
Time _t;
public:
entry(int sno=5,Time t = Time(1,2,'p')):
_t(t), _sno(sno)
{};
void showdata()
{
cout<<"ne : "<< _sno<<" : ";
_t.showtime();
}

};

int main()
{
entry e;
e.showdata();
Time t2(5,2,'a');
entry e2(3, t2);
e2.showdata();
return 0;
}

最新更新