c++ - 继承访问问题
问题描述
在执行以下与继承相关的代码时,出现以下错误“使用已删除的函数 'Derived::Derived'”。同样在注释中说,“Derived::Derived() 被隐式删除,因为默认定义会被告知错误”。有人可以帮我解决这个问题:
#include <iostream>
//BASE CLASS
class Base
{
public:
int a;
void display()
{
std::cout << "a = " << a << ", b = " << b << ", c = " << c << std::endl;
}
//constructor
Base(int la, int lb, int lc) : a {la}, b {lb}, c {lc}
{
}
protected:
int b;
private:
int c;
};
//DERIVED CLASS
class Derived : public Base
{
//a from Base is Public
//b from Base is Protected
//c from Base has No access
public:
void access_base_members()
{
a = 100; //OK since a is Public in parent
b = 200; //OK since b is Protected type in Parent. So derived CLASS will have access
//c = 300; //NOK since c is private in parent and hence cannot be accessed
}
};
int main()
{
std::cout << "\nBase Member access=>\n\n";
Base base(1,2,3);
base.a = 10; //OK
//base.b = 20; //NOK since Protected
//base.c = 30; //NOK since Private
base.display();
Derived derived;
derived.a = 111; //OK since public in parent
//derived.b = 222; //NOK since protected members cannot have direct access in OBJECTS
//derived.c = 333; //NOK since private
}
解决方案
基类没有隐式默认构造函数,因为有显式声明的构造函数
Base(int la, int lb, int lc) : a {la}, b {lb}, c {lc}
{
}
所以默认必须调用基类默认构造函数的派生类默认构造函数定义为删除。
因此,编译器为此声明发出错误消息
Derived derived;
您需要显式定义派生类的构造函数。
例如,您可以将其定义为
Derived() : Base( 0, 0, 0 )
{
}
或/和
Derived(int la, int lb, int lc ) : Base( la, lb, lc )
{
}
推荐阅读
- python - Python中的异步URL取消缩短
- oracle - Liquibase 忽略 Oracle DB 的 autoIncrement="true"
- flutter - 我应该如何应用此代码来处理颤振?
- jquery - 无法重新加载 Datatables 服务器数据
- c# - 在 WPF 调度程序调用中等待
- java - 在jenkins中执行时如何将参数从pom.xml动态传递给java类
- php - Laravel App\Mail - 为 foreach() 提供的参数无效 - 邮件
- java - 在 JavaFX / fxml 中打开新窗口,但我不希望它打开新场景
- java - AlertDialog 按钮区域背景颜色 Android
- angular - 如何在切换之前为组件设置动画
到下一个组件?