[英]Member functions of a derived class
When a class is derived from a base class, will the member functions of the base class become member function of the derived class. 当类从基类派生时,基类的成员函数是否将成为派生类的成员函数。 That is, for example if I write:
也就是说,例如,如果我写:
class A
{
public : void f();
};
class B : public A
{
public : void f1();
};
Now if the question is to name the member functions in class B, then will f() also become a member function of class B ? 现在如果问题是在B类中命名成员函数,那么f()也会成为B类的成员函数吗?
Yes, class B
has two functions: f1()
and f()
. 是的,
B
类有两个功能: f1()
和f()
。
If f()
was protected
in A
, too, but f()
could only be used from within the member functions of A
and B
(and from friend
s). 如果
f()
也在A
中protected
,但f()
只能在A
和B
(以及来自friend
)的成员函数中A
。
And if f()
was private
, B
would have only one function f1()
. 如果
f()
是private
, B
只有一个函数f1()
。
class A {
public : void f();
};
class B : public A
{
public : void f1();
};
Now code is valid. 现在代码有效。 It is visible.
它是可见的。 Even when you change f1 name to f it is still visible in B class.
即使将f1名称更改为f,它仍然可以在B类中看到。 If you wanna use it use scope operator ::.
如果你想使用它,请使用范围运算符::。
Like this: 像这样:
A::f()
More about basic inheritence http://www.learncpp.com/cpp-tutorial/112-basic-inheritance-in-c/ 关于基本遗产的更多信息http://www.learncpp.com/cpp-tutorial/112-basic-inheritance-in-c/
then will f() also become a member function of class B ?
那么f()也会成为B类的成员函数吗?
No. f()
is still a member function of class A
, class B
just inherits it. 编号
f()
仍然是A
类的成员函数, B
类只是继承它。 In your case it's a public member function and public inherit, means you can call f()
on a B
object. 在你的情况下,它是一个公共成员函数和公共继承,意味着你可以在一个
B
对象上调用f()
。
B b;
b.f();
On the other hand, class B
can define own member function f()
: 另一方面,
B
类可以定义自己的成员函数f()
:
class A
{
public : void f();
};
class B : public A
{
public : void f(); // will hide A::f()
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.