I am using a struct variable inside a class and I would like to assign the value of a parameter of that variable in the class constructor.
But I can not find a way to compile. could you show me how to do it? This is an example of my code
struct mystruct
{
int myvar;
}
class myclass
{
mystruct s_;
public:
myclass(int n) : s_.myvar{ n } {}
};
Your mystruct
would need a suitable constructor which takes an int
ger as an argument, for that.
struct mystruct
{
int myvar;
mystruct(int val) // provide this constructor and good to go!
: myvar{ val }
{}
};
Or Aggregate Initialization
Since mystruct
is an aggregate type you could do the aggregate initialization too. This would be the minimal change required for your case and do not require the constructor in mystruct
.
class myclass
{
mystruct s_;
public:
myclass(int n)
: s_{ n } // aggregate initialization
{}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With