问题
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