简体   繁体   English

C ++纯虚拟const成员函数

[英]C++ pure virtual const member function

How can I declare a pure virtual member function that is also const? 如何声明一个纯const的虚拟成员函数? Can I do it like this? 我可以这样做吗?

virtual void print() = 0 const;

or like this? 或者像这样?

virtual const void print() = 0;

From Microsoft Docs : 来自Microsoft Docs

To declare a constant member function, place the const keyword after the closing parenthesis of the argument list. 要声明常量成员函数,请将const关键字放在参数列表的右括号之后。

So it should be: 所以它应该是:

virtual void print() const = 0;

Only the virtual void print() const = 0 form is acceptable. 只有virtual void print() const = 0表单是可以接受的。 Take a look at the grammar specification in C++03 §9/2: 看一下C ++03§9/ 2中的语法规范:

member-declarator : 成员声明者
declarator pure-specifier opt 声明者纯粹指定者选择
declarator constant-initializer opt 声明器常量初始化器选择
identifier opt : constant-expression identifier opt : constant-expression

pure-specifier: 纯符:
= 0

The const is part of the declarator -- it's the cv-qualifier-seq opt in the direct-declarator (§8/4): const声明 const的一部分 - 它是直接声明符(§8/ 4)中的cv-qualifier-seq opt

declarator : 声明者
direct-declarator 直接说明符
ptr-operator *declarator* ptr-operator *声明者*

direct-declarator : 直接声明者
declarator-id 声明符-ID
direct-declarator ( parameter-declaration-clause ) cv-qualifier-seq opt exception-specification opt direct-declarator ( parameter-declaration-clause ) cv-qualifier-seq opt exception-specification opt
direct-declarator [ constant-expression opt ] 直接声明符 [ constant-expression opt ]
( declarator ) ( 声明者 )

Hence, the = 0 must come after the const . 因此, = 0必须在const

Of course you can. 当然可以。 The correct syntax is: 正确的语法是:

virtual void print() const = 0;

试试这个:-

 virtual void print()  const = 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM