Issue
I'm trying to do this:
class test{
public:
struct obj{
int _objval;
};
obj inclassobj;
int _val;
test(){}
test(int x):_val(x){}
test(int x, int y): _val(x), inclassobj._objval(y){}
};
It doesn't work. Unless I put in-class struct part in to the body of the constructor like this:
test(int x, int y){
_val = x;
inclassobj._objval = y;
}
This way works fine. Then I find someone said unless I can give my in-class object it's own constructor, then I did this, it doesn't work:
class test{
public:
struct obj{
int _objval;
obj(){}
obj(int val): _objval(val){}
};
obj inclassobj(6);
};
The error pops up at the line where I'm trying to instantiated obj
: obj inclassobj(6);
I have totally no idea about this. The first question is why I can't use constructor initializer list to initialize a in-class struct in this case? If the reason is I need to give that struct a constructor, why the second part is also doesn't work?
update:: I realize I can use a pointer to initialize the in-class object like this:
class test{
public:
struct obj{
int _objval;
obj(){}
obj(int val): _objval(val){}
};
obj* inclassobj = new obj(6);
};
But why?
Solution
In your 2-param constructor, you can use aggregate initialization of the inner struct, eg:
test(int x, int y): _val(x), inclassobj{y}{}
In your second example, adding a constructor to the inner struct is fine, you just need to call it in the outer class's constructor member initialization list, eg:
test(int x, int y): _val(x), inclassobj(y){}
Answered By - Remy Lebeau Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.