[英]c++ pure virtual functions with a body
我最近才知道,在C ++中,纯虚函数可以有一个主体。
我知道虚函数的主体存在是因为我想从派生类中调用她,但是我可以这样做吗?
class Base{
int x;
public:
virtual void print()=0;
};
void Base::print(){
cout << x;
}
class Derived : public Base{
int y;
public:
void print(){
Base::print();
cout << y;
}
};
结果将是:x的值,然后是y的值?
我真正的意思是,函数Base :: print()会知道从Derived类的函数中获取x的值?
对于以下代码,输出将为“ 12”,因此,是的,将调用带有主体的纯虚函数,然后调用派生的print。 因此,是的,结果将是:x的值,然后是y的值,就像您猜到的那样。 这是有效的C ++,是的,它将知道如何在这种情况下获得“ x”。
有效的C ++” Scott Meyers提到了纯虚函数具有主体的原因:实现此纯虚函数的派生类可以在其代码中调用此实现。如果两个不同派生类的部分代码相似,则它将使即使功能应该是纯虚拟的,也可以在层次结构中向上移动它。
#include <iostream>
using namespace std;
class Base{
int x;
public:
Base(): x(1) {}
virtual void print()=0;
};
void Base::print(){
cout << x;
}
class Derived : public Base{
int y;
public:
Derived(): Base(), y(2) {}
void print(){
Base::print();
cout << y;
}
};
int main()
{
Derived d;
d.print();
return 0;
}
输出: 12
抽象函数当然可以有一个实现,并且在抽象析构函数的情况下,甚至需要仍然实现该函数(将析构函数virtual
并不意味着只有派生的析构函数才被调用)。 ...,而抽象函数的实现仍然只是可以访问其类成员的普通函数。
在您的示例中, x
是Base
的成员。 Base::print()
可以访问Base
的私有成员是什么呢?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.