我是 OOP 的新手。最近在C++中学习了一些关于继承的知识,一个protected字段不能从类外访问,但是可以在继承类中访问。我的代码有一些问题,我不明白出了什么问题:
class Base
{
protected:
int x;
int y;
int z;
public:
Base(int a, int b): x(a), y(b) { cout << "Base constructor" << endl; };
Base(const Base& prev) : x(prev.x), y(prev.y) { cout << "Base copy constructor" << endl; };
void print_x()
{
cout << x << endl;
}
void print_y()
{
cout << y << endl;
}
~Base() { cout << "Base destructor" << endl; };
};
class Derived : public Base
{
public:
Derived(int a, int b): x(a), y(b) { cout << "Derived constructor" << endl; }; ////////ERROR : Class
'Derived' does not have any fields named 'x' and 'y'
};
int main()
{
Base* b = new Base(10, 20);
Derived* d = new Derived(10, 20);
delete b;
delete d;
return 0;
}
如果Derived继承Base,为什么编译器说Derived没有字段x和y?