C++类外的虚函数实现
我是 C++ 新手。在尝试示例多态性代码时,我发现派生类中的基类虚函数定义只有在派生类内部定义或在派生类中声明外部时才可能。
以下代码给出错误:
class B
{
public:
virtual void f();
};
void B::f() {
std::cout<<"B::f";
}
class D : public B
{
public:
void f2() {int b;}
};
// error: no "void D::f()" member function declared in class "D"
void D::f() {
std::cout<<"D::F";
}
如果我在 D 中声明 f() ,它就会起作用。我想知道为什么当函数已经在基类中声明时,我需要再次显式声明该函数。编译器可以从基类获取签名吗?
提前致谢..
I am new to C++. While trying sample polymorphism code, I found that base class virtual function definition in derived class is possible only when defined within the derived class or outside with declaration in derived class.
Following code gives error:
class B
{
public:
virtual void f();
};
void B::f() {
std::cout<<"B::f";
}
class D : public B
{
public:
void f2() {int b;}
};
// error: no "void D::f()" member function declared in class "D"
void D::f() {
std::cout<<"D::F";
}
It works if I declare f() inside D. I was wondering why do I need to explicitly declare the function again when it is already declared in Base class. The compiler can get the signature from Base class right?
Thanks in advance..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不能将成员添加到类定义之外的类中。如果您希望
D
覆盖B::f
,那么您必须在类定义中声明它。这些就是规则。在基类中声明成员不会自动为派生类提供相同的成员。从基类继承为派生类提供了基类的所有成员,因此您可以选择是否重写、隐藏或添加基类成员,但必须通过声明重写函数来在类定义中指示重写的选择。
You can't add members to a class outside of the class definition. If you want
D
to have an override forB::f
then you have to declare it inside the class definition. Those are the rules.Declaring a member in a base class doesn't automatically give derived classes an identical member. Inheriting from the base gives the derived class all the members of the base class so you can choose whether to override, hide or add to the base classes members but you have to indicate a choice to override in the class definition by declaring the overriding function.
尽管 D 派生自 B,因此您可以在 D 的实例上调用 f(),但这并不意味着您不需要将声明放入标头中。
您实现的任何函数都必须在标头中显式声明。
但是,您不需要将其实现放在那里。只是
您可以选择是否在此处包含“虚拟”一词
Even though D derives from B and therefore you can call f() on an instance of D, it does not mean you do not need to put the declaration into the header.
Any function you implement must be explicitly declared in the header.
You do not need, however, to put its implementation in there. Just
and you can optionally choose whether to include the word "virtual" here
在 C++ 中,类定义告诉编译器该类实现了哪些函数。因此,如果要编写函数“D::f()”,则必须在 D 的类定义中包含 f()。
函数“B::f()”已在基类中定义的事实是无关紧要。每个类定义必须显式声明它实现的函数。
In C++, your class definition tells the compiler which functions the class implements. So if you want to write a function "D::f()", you must have f() in the class definition for D.
The fact that function "B::f()" has been defined in the base class is irrelevant. Each class definition must explicitly declare the functions that it implements.
更改 D 类的代码如下并尝试:
Change code for class D as below and try :