簡體   English   中英

如果一個類包含另一個類的對象,是否可以通過在 C++ 中包含類的構造函數中使用默認值來初始化它?

[英]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(int sno=5,time t{1,2,'p'}); entry類的構造函數中有效嗎? 如果一個類包含另一個類的復雜對象,那么它可以通過這種方式初始化嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM