C++ private variable with no default ctor - not co

2019-02-26 23:26发布

I have a class obj1 that has no default constructor, and class obj2 that also doesn't have a default constructor, and has as private variable an element of obj1:

I would like something like the following code - but actually this doesn't compile, telling me that obj1 has no default constructor.

class obj1{
    obj1(some parameters){};
}

class obj2{
    obj1 _myObj1;
    obj2(some parameters){
        _myObj1 = obj1(some parameters)
    }
} 

any ideas?

4条回答
Root(大扎)
2楼-- · 2019-02-26 23:29

You need to make the constructor accessable to class obj2. This can be accomplished by making it public so that all other classes can use it or you can mark obj2 as a friend of obj1.

class obj2;

class obj1{
    obj1(some parameters){};
    friend class obj2;
}

class obj2{
    obj1 _myObj1;
    obj2(some parameters){
        _myObj1 = obj1(some parameters)
}

or mark the constructor as public

obj1 {
public:
    obj1(some parameters){};
}
查看更多
三岁会撩人
3楼-- · 2019-02-26 23:31

You must put your constructor in public area:

class obj1{
    public:
    obj1(some parameters){};
}

and even you second class:

    class obj2{
        obj1 _myObj1;
        public:
        obj2(some parameters) : _myObj1(some parameters){
        }
    } 

More:

In fact, private constructors are useful when you want forbid your code to instance an object directly. The most popular usage of private constructors are Singleton classes.

查看更多
三岁会撩人
4楼-- · 2019-02-26 23:50

Make the constructor of obj1 public and use initialization list in obj2.

class obj1{
public:
    obj1(some parameters){};
};

class obj2{
    obj1 _myObj1;
    obj2(some parameters) : _myObj1(some parameters) {
    }
};
查看更多
手持菜刀,她持情操
5楼-- · 2019-02-26 23:52

You need to make your constructors public and you need to call the obj1 in the initialization list of obj2 constructor.

class obj1{
public:
    obj1(some parameters){};
}

class obj2{
    obj1 _myObj1;
public:
    obj2(some parameters) : _myObj1(some parameters)
    {
    }
} 
查看更多
登录 后发表回答