如何从 B 继承类 A,同时从 A 继承 B
How to inherit class A from B while inheriting B from A?
本文关键字:继承 更新时间:2023-10-16
所以我有 2 个类,即 book
和 mainscreen
,其中 book
是公开继承自mainscreen
的。
现在我想通过主屏幕的成员函数使用类书的公共成员函数。
这是我的代码:
class book;
class mainscreen:virtual public book
{
protected:
int logged;
public:
void printmenu();
void printhead();
void auth();
void logout();
mainscreen();
};
class book:public mainscreen
{
private:
int bookno,
days,
late_days;
long double price;
float fine_calc(int a,float b) // a -> late days , b -> fine per day
{
return a*b;
}
public:
book(); //const
void input();
void display();
void update();
};
调用部分:-
void mainscreen::printmenu(){
int i;
printhead();
cout<<"nnt Choose a Number to perform the corresponding task n";
cout<<"n1.Enter a new Book ";
cout<<"n2.Issue a Book ";
cout<<"n3.Return a book" ;
cout<<"n4.Update Information for a book ";
cout<<"n5.Information About books ";
cout<<"n6.Logout ";
cout<<"nEnter your choice: ";
cin>>i;
menuhandler(i);
}
void mainscreen::menuhandler(int choice){ //the no of choice selected
switch(choice)
{
case 1: printhead();
input();
case 2: printhead();
issuebook();
case 3: printhead();
returnbook();
case 4: printhead();
update();
case 5: printhead();
display();
case 6: logout();
default:
cout<<"Invalid Choice! Press Return to Try again. ";
getch();
printmenu(); // Reset to menu
}
}
当我尝试在 mainscreen
的成员函数中使用类 book
的公共成员函数时,我收到以下错误:调用未定义的函数。
你有:
- 标识了两个实体(类(:
Book
和MainScreen
- 然后,您确定了这些类的常见行为和属性
然而,你得出了非常错误的结论,即这些类应该相互继承(即相互提供一些行为/属性(。相反,您应该做的是创建第三个类,这些类将从中继承(无论它们的共同点是什么(。
例如,一种可能的基于接口的方法可能是:
class Displayable {
public:
virtual void display();
};
class Book : public Displayable {
...
};
class MainScreen : public Displayable {
...
};
相关文章:
- 继承函数的重载解析
- 继承期间显示未知行为的子类
- 头文件-继承c++
- 为什么在保护模式下继承升级不起作用
- 通过继承类使用来自不同命名空间的运算符
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 混合组合和继承的C++问题
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 公共与私人继承
- 如何创建从同一类继承的不同对象的向量
- 如何从另一个文件继承私有成员变量和公共函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 带有继承的C++工厂
- 我应该避免多重实现继承吗
- C++继承更改成员
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 关于C++中具有多重继承"this"指针的说明
- 尝试使用继承和模板实现CRTP.Visual Studio正在生成编译器错误
- 如何在QT Creator上将QWidget声明为继承类的对象