在不使用public或private的情况下继承其他类 [英] Inheriting other class without using public or private
本文介绍了在不使用public或private的情况下继承其他类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尊敬的老年人,
您能否在不指定public或private的情况下给出一些关于我到底如何能够继承其他类的功能的提示.如果我能够,那么什么时候才应该使用公共或私人
以下是示例代码段供您参考.
Dear Seniors,
Can you please give some hints on how exactly i am able to inherit the functions of other class with out specifying either public or private. If i am able to then when only should I use public or private
Below is the sample code snippet for your reference.
#include <iostream>
#include <string>
class A
{
private:
std::string name;
public:
void getdata( )
{
std::cout << "Name: ";
std::cin >> name;
}
void showdata( )
{
std::cout << "Your name: " << name << std::endl;
}
};
class B
{
private:
std::string surname;
A a;
public:
void getdata( )
{
a.getdata( );
std::cout << "Surname: ";
std::cin >> surname;
}
void showdata( )
{
a.showdata( );
std::cout << "Your surname: " << surname << std::endl;
}
};
int main( )
{
B e;
e.getdata( );
e.showdata( );
return 0;
}
问候,
Kiran
Regards,
Kiran
推荐答案
这里根本没有继承.
您只是在创建class A
的对象作为class B
的成员变量.
这与在类内部或main
函数中的class B
对象中创建std::string
对象的方式相同.
因此,例如,您将无法执行任何多态性.
A* ptr = new B;
将引发错误,因为这需要继承.
There is no inheritance here at all.
You''re simply creating an object ofclass A
as a member variable ofclass B
.
This is the same as how you created astd::string
object inside the class or an object ofclass B
in themain
function.
So, for example, you will not be able to perform any polymorphism.
A* ptr = new B;
will throw an error because this needs inheritance.
这篇关于在不使用public或private的情况下继承其他类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文