抽象类和纯方法
Abstract class and pure method C++
我在Stephen Prata的《c++ Primer Plus VI Edition》一书中读到,我可以在抽象类中编写纯方法的定义。我知道我可以写,例如,void pure() = 0
,然后我可以在这门课上定义这个方法。我认为= 0
只是为了使类抽象,如果我从该类继承另一个类,我不必覆盖它(我不知道"覆盖"这个词是否正确,我的意思是我不想通过在二级类中编写具有相同名称的方法来隐藏基本类的方法)。
我在编译器中检查了它,我得到警告,"它没有覆盖"。因此,如果我必须在二级类中覆盖这个纯虚方法(在抽象类中定义),我如何使用基本类中的定义?这没用吗?
你在找这样的东西吗?
class Abstract {
public:
virtual void f() = 0;
};
// A pure virtual function can still be defined.
// It has to be defined out-of-class.
void Abstract::f() {
// Do something
}
class Concrete : public Abstract {
public:
void f() {
Abstract::f(); // call base class implementation
// Do something more
}
};
下面是一个解释纯函数概念的例子
#include <iostream>
struct A
{
virtual ~A() = default;
virtual void what() const = 0;
};
void A::what() const
{
std::cout << "struct A";
}
struct B : A
{
virtual void what() const = 0;
};
void B::what() const
{
A::what();
std::cout << ", struct B : A";
}
struct C : B
{
void what() const;
};
void C::what() const
{
B::what();
std::cout << ", struct C: B";
}
int main()
{
// A a; compiler error
// B b; compiler error
C c;
const A &rc = c;
rc.what();
std::cout << std::endl;
return 0;
}
程序输出为
struct A, struct B : A, struct C: B
在这个例子中,类A和类B是抽象的,因为它们有一个纯虚函数,尽管它们每个都提供了它们的纯虚函数的相应定义。
只有类C不是抽象的,因为它将虚函数重新声明为非纯虚函数。
如果要实例化继承的类,即创建该类型的对象,则必须在继承的类中实现所有纯虚方法。
换句话说,纯虚方法不仅定义类接口,而且还强制您提供它们的实际实现。
相关文章:
- 对纯抽象类中方法的未定义引用
- 用c++中的纯虚拟方法抽象模板类
- 无法实例化抽象类,但类不是抽象/派生方法的参数
- 抽象类/接口中的空方法是否被认为是一种好的做法?
- 如何使用抽象类中未包含的方法
- 确保派生的类实现至少是来自抽象类(C )的两种方法之一
- C :如何在此抽象类的方法中返回抽象类
- 我将如何通过抽象类传递虚拟方法,但可以选择不重写
- 从子类中的抽象类调用方法
- 如何通过方法使用抽象类的子实例?
- 抽象类的需求是什么?为什么要通过其基类访问派生类方法?在C++
- 派生类使用的抽象类的方法
- 使用智能指针将右值引用绑定到抽象类的替代方法
- 在抽象基类中与抽象类成员合作的最佳方法
- 使用纯虚拟方法在C 中初始化抽象类
- C++中的抽象类和纯虚方法
- 我们可以通过在C++中的类中使用关键字“abstract”使所有方法抽象来声明接口类吗
- 带有抽象类的unique_ptr成员和Copy构造函数的Factory方法模式
- C++抽象类参数错误解决方法
- 我们是否有更好的方法来返回C++中的抽象类