这可能不是一个好问题,我知道我需要更多的时间来了解它
但我真的很想知道如何让它工作
这是我的代码
#include <bits/stdc++.h>
using namespace std;
class Parent{
protected:
int value;
int size;
public:
Parent();
Parent(const Parent &p);
};
Parent::Parent()
{
this->value = 0;
this->size = 0;
}
Parent::Parent(const Parent &p)
{
this->value = p.value;
this->size = p.size;
}
class Child:public Parent{
public:
Child();
Child(const Parent& p);
};
Child::Child()
{
this->value = 0;
this->size = 0;
}
Child::Child(const Parent& p)
{
this->value = ??
this->size = ??
}
由于我想在继承的子类中使用父类作为参数,
问题是我不能在子类中用p.size或p.value
有什么办法解决这个问题吗
感谢您阅读本文。
在您的情况下:Child::Child(const Parent& p) : Parent(p) {}
此Child(const Parent& p);
不是正确的复制构造函数。类T
的复制构造函数采用&T
(可能带有CV限定符)作为参数。在这种情况下,它应该是Child(const Child& p);
。
此外,如果我们看看https://en.cppreference.com/w/cpp/language/access,那么我们可以看到:
类的受保护成员只能访问
- 致会员和那个阶层的朋友
- 的成员和朋友(直到C++17)该类的任何派生类,但仅当对象的类通过其访问受保护成员的是派生类或该派生类的派生类
因此,Child
中以Child
为参数的函数可以访问其他Child
的受保护成员,但以Parent
为参数的功能无法访问该Parent
的受保护的成员。
例如,如果您的Button
和TextBox
都继承自UIWidget
,则Button
可以访问其他Button
中受UIWidget
保护的成员,但不能访问TextBox
中的。
编辑:
如果你真的想有一个以Parent
为自变量的构造函数,那么你可以按照Roy Avidan在他的回答中建议的那样做:
Child::Child(const Parent& p)
: Parent(p) // <- Call the Parent copy constructor
{
// No access to protected members of p here!
}
这是因为它使用Parent
参数调用Parent
的复制构造函数,这意味着对Parent
的受保护成员的任何访问都发生在Parent
中。注意,对主体中p
的受保护成员的任何访问都是对p
的访问违规。