[英]How to call child class function from parent class?
I'm new to C++ language and I'm doing library Management System. 我是C ++语言的新手,并且正在做库管理系统。 i have a classes like this.
我有这样的课程。 eg:
例如:
class mainLibrary{
void library(){
cout<<"Welcome to Our Library. Please choose following options"<<endl;
cout<<"1. Member Section, 2. Lending Section"<<endl;
if(userinput==1){
memberclassfunction();//Error : use of undeclared identifier 'memberclassfunction'.
}else{
lendingclassfunction();//Error : use of undeclared identifier 'lendingclassfunction'.
}
}
};
class Member:public mainLibrary{
void memberclassfunction(){
//do something
}
};
class lending:public Member{
void lendingclassfunction(){
//do something
}
};
class mainSystem:public lending{
//this is empty and inherit all.
};
void main{
mainSystem s1;
s1.library();
}
i did something like this. 我做了这样的事情。 but in mainLibrary Class if i call memberclassfunction();
但是在mainLibrary类中,如果我调用memberclassfunction(); program show me error.
程序显示错误。 use of undeclared identifier 'memberclassfunction'.
使用未声明的标识符“ memberclassfunction”。
can anyone help me how to do that. 谁能帮助我做到这一点。 i think i have to do something with pointers right?
我想我必须对指针做些事情对吗?
memberclassfunction必须是mainLibrary中的虚函数,这意味着mainLibrary将成为一个接口,您将无法实例化它。
Neither memberclassfunction
nor lendingclassfunction
are members of class mainLibrary
, that's why the compiler is giving you these errors. memberclassfunction
和lendingclassfunction
都不是lendingclassfunction
类的mainLibrary
,这就是编译器向您显示这些错误的原因。 I think your intention was to make these functions virtual
. 我认为您的意图是使这些功能
virtual
。
Whenever class B
inherit from class A
, the former gets the latter's members, not the other way around. 每当
B
类从A
类继承时,前者将获得后者的成员,而不是相反。
Generally it's not a good idea to have a base class depend on methods in its sub-classes. 通常,让基类依赖于其子类中的方法不是一个好主意。 However if you MUST do this, you could always cast
this
to the subclass and if the cast succeeds then you can call the method. 但是,如果你必须这样做,你总是可以投
this
子类,如果转换成功,那么你可以调用该方法。
lending *lendingThis = dynamic_cast<lending *>(this);
if (lendingThis) {
lendingThis->lendingclassfunction();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.