在c++中,如何在继承的子类中使用父类作为参数

  • 本文关键字:父类 参数 c++ 继承 子类 c++
  • 更新时间 :
  • 英文 :


这可能不是一个好问题,我知道我需要更多的时间来了解它
但我真的很想知道如何让它工作
这是我的代码

#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,那么我们可以看到:

类的受保护成员只能访问

  1. 致会员和那个阶层的朋友
  2. 的成员和朋友(直到C++17)该类的任何派生类,但仅当对象的类通过其访问受保护成员的是派生类或该派生类的派生类

因此,Child中以Child为参数的函数可以访问其他Child的受保护成员,但以Parent为参数的功能无法访问该Parent的受保护的成员。

例如,如果您的ButtonTextBox都继承自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的访问违规。

最新更新