Class A
contains the protected int x
. Class B
extends class A
. Now what class B
wants to do is set the value of x
as a passing argument in its own constructor. When I try to do that, I get the error:
""x" is not a non-static data member or base class of class "B"".
#include <string>
#include <iostream>
class A {
protected:
int x;
public:
A()
{
}
};
class B : public A {
public:
B(int x)
: x(x)
{
}
};
int main()
{
}
You can "set" it, but not initialize it, because it has already been initialized when the base class object gets initialized. You can "set" it like this:
B(int x)
{
this->x = x; // assignment, not initialization
}
It would make more sense for one of A
's constructors to take care of the initialization of A::x
:
A(int x) : x(x) {}
and then use that in B
:
using A::A; // allows B b{42};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.