在 C++ 中,为什么纯函数必须是虚函数?
In C++ why a pure function must be virtual?
我在 google 和此处进行了搜索,但我不明白为什么 class 中的纯函数必须是虚函数。我知道将 "normal function" 声明为 pure 可能不是很有用,但我认为这不是废话。我的意思是,"pure" 这个词只是为了声明一个抽象 class。好的,我不能将多态与那个纯正常函数一起使用,但无论如何达到了主要原因(将 class 声明为抽象)。
我错了吗?
没有要求纯函数必须是虚函数。如果您正在考虑术语 "pure virtual function",那么 "pure" 适用于 "virtual";该功能是纯虚拟的。这是 "pure".
这个词的不同用法
I mean, the word "pure" is there just to declare an abstract class.
不是。声明纯虚函数的原因不是为了阻止实例化封闭 class;是为了保证具体的子class实现方法,通常是因为抽象class无法提供合理的实现。
Ok, I can not use polymorphism with that pure normal function but the main reason (declare a class as abstract) is reached anyway.
如果您正在寻找一种无需任何纯虚函数即可声明 class 抽象的方法,C++ 没有专门用于此的语法。我看到的建议是 declare and implement a pure virtual destructor (you can do that), or to make the constructor protected (but making the constructor protected won't make your class pass std::is_abstract
)。在任何情况下,将语法附加到任意成员函数都没有多大意义; class Foo = 0 { ... };
这样的东西更有意义。
您想要 "pure function" 的唯一原因是确保从 class 继承的子 class 定义此函数的实现。如果您允许纯函数是非虚拟的,因此不能被覆盖,那么它们基本上毫无意义。
我在 google 和此处进行了搜索,但我不明白为什么 class 中的纯函数必须是虚函数。我知道将 "normal function" 声明为 pure 可能不是很有用,但我认为这不是废话。我的意思是,"pure" 这个词只是为了声明一个抽象 class。好的,我不能将多态与那个纯正常函数一起使用,但无论如何达到了主要原因(将 class 声明为抽象)。 我错了吗?
没有要求纯函数必须是虚函数。如果您正在考虑术语 "pure virtual function",那么 "pure" 适用于 "virtual";该功能是纯虚拟的。这是 "pure".
这个词的不同用法I mean, the word "pure" is there just to declare an abstract class.
不是。声明纯虚函数的原因不是为了阻止实例化封闭 class;是为了保证具体的子class实现方法,通常是因为抽象class无法提供合理的实现。
Ok, I can not use polymorphism with that pure normal function but the main reason (declare a class as abstract) is reached anyway.
如果您正在寻找一种无需任何纯虚函数即可声明 class 抽象的方法,C++ 没有专门用于此的语法。我看到的建议是 declare and implement a pure virtual destructor (you can do that), or to make the constructor protected (but making the constructor protected won't make your class pass std::is_abstract
)。在任何情况下,将语法附加到任意成员函数都没有多大意义; class Foo = 0 { ... };
这样的东西更有意义。
您想要 "pure function" 的唯一原因是确保从 class 继承的子 class 定义此函数的实现。如果您允许纯函数是非虚拟的,因此不能被覆盖,那么它们基本上毫无意义。