C++ private variable with no default ctor - not compiling?

佐手、 提交于 2019-12-02 03:34:22

问题


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?


回答1:


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) {
    }
};



回答2:


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)
    {
    }
} 



回答3:


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:


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){};
}


来源:https://stackoverflow.com/questions/8201402/c-private-variable-with-no-default-ctor-not-compiling

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!