简体   繁体   中英

C++:creating default constructor for a class that owns a class member(the member lacks default constructor)

The problem is based on c++ primer 5th edition 7.43.

    #include<iostream>
    using namespace std;
    class C;
    class NoDefault{
    friend class C;
    public:
        NoDefault(int a) :item(a) {}   //lack default constructor
    private:
        int item;
    };
    class C{
    public:
        C() :item(1){}  //default constructor
        void print();
    private:
        NoDefault item;
    };
    void C::print()
    {
        cout<<item.item;
    }
    int main()
    {
        C obj1;
        obj1.print();
        return 0;
    }

The excecution of the program display no output and just ends directly. I think the output should be 1,because the following initializing process:

    C() :item(1){}  //default constructor
    NoDefault(int a) :item(a) {} 

Please point out my mistake,many thanks!

Thanks for the help from people who answered my question! The code I posted was correct and the problem is something wrong with my compiler...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM