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

If a class contains object of another class can it be initialized by having default value in the constructor of containing class in C++?

编译此代码产生错误

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

我试图减少重载的构造函数,所以我试图在构造函数参数中提供默认值。 entry class 的构造函数中的 entry(int sno=5,time t{1,2,'p'}); 行是否有效?如果一个 class 包含另一个 class 的复杂对象,那么它可以这样初始化吗?

#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;
}