c++纯虚拟函数与实体
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()将知道从派生类中的函数中获取x的值????
以下代码的输出将为"12",因此是的,将调用带有主体的纯虚拟函数,然后调用派生的print。所以,是的,结果是:x的值,然后是y的值,正如你所猜测的那样。这是有效的C++,是的,它将知道如何在该上下文中获得"x"。
有效C++"Scott Meyers提到了纯虚拟函数具有主体的原因:实现该纯虚拟函数的派生类可以在其代码中调用该实现smwhere。如果两个不同派生类的部分代码相似,则在层次结构中向上移动它是有意义的,即使该函数应该是纯虚拟的。
#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
的私人成员有什么令人惊讶的?
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 返回模板化实体的函数的概念
- 无法将错误分配给成员函数中"类型的实体"
- Lua到c++,用于实体修改的实例化函数
- 摆脱在Qt QGlWidget中绘制实体对象的glut函数
- c++纯虚拟函数与实体
- oxygen中的关键字,它将显示当前使用函数的实体
- 通用打印函数,可以处理列表和标量实体