简体   繁体   English

在public const修饰符中使用变量

[英]Using variable with public const modifier

I'd like to have a variable in my class that is const when accessed from public scope and non- const when accessed from a private or protected scope. 我想在我的类中有一个变量,当从public作用域访问时为const ,而从private或受保护范围访问时为非const I'd like to avoid having a getter-method that returns a const reference to the variable. 我想避免使用一种getter方法来返回对该变量的const引用。 I tried messing around with the using keyword, but no success so far. 我尝试弄乱using关键字,但到目前为止没有成功。 Ideally it would look something like this: 理想情况下,它看起来像这样:

class Foo
{
public:
    using var = const m_var; // This is of course gibberish
private:
    int m_var;
}

I could add a public const reference member variable and let it point to the private variable, but that way my class would get 4 bytes bigger, which I would like to avoid. 我可以添加一个公共的const引用成员变量,并使其指向私有变量,但是那样,我的类将增加4个字节,这是我想避免的。 Would a compiler realize that and optimize out that reference? 编译器会意识到这一点并优化参考吗?

Any other ideas on how to solve the problem? 关于如何解决问题还有其他想法吗?

I'd like to avoid having a getter-method that returns a const reference to the variable 我想避免使用getter方法来返回对变量的const引用

I don't know why you'd like to avoid that. 我不知道您为什么要避免这种情况。 This sounds like exactly what you want (perhaps just returning by-value): 这听起来像是您想要的(也许只是返回按值):

class Foo
{
public:
    int getVar() const { return m_var; }
protected:
    int m_var;
};

If you have protected or private access to Foo , you can just m_var . 如果您具有对Foo protectedprivate访问,则只需m_var If you don't, then you have a public const getVar() that doesn't let you modify it. 如果不这样做,那么您将拥有一个公共const getVar() ,该常量getVar()您对其进行修改。


There's really no other way of doing this. 确实没有其他方法可以做到这一点。 You can't overload on access rights in the way you can have overload on const -qualification or ref-qualification since overload resolution happens before access checking. 您不能像使用const -qualification或ref-qualification那样重载访问权限,因为重载解析发生在访问检查之前。 That prohibits you from doing something like having a protected and public overload where the protected overload is the better match. 那会禁止您执行protected public过载之类的事情,而protected过载更适合。

You also can't add aliases for variables without introducing actual references - but at that point you're making your class bigger but you still are using different names to reference the public and protected anyway, at which point using the public accessor member function is strictly better. 您也不能在不引入实际引用的情况下为变量添加别名-但那时候您是在扩大类的大小,但是无论如何仍在使用不同的名称来引用publicprotected ,此时使用public访问器成员函数是严格更好。

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

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