C ++中有没有一种方法可以创建“超级私有"变量? [英] Is there a way in C++ to create 'super private' variables?

查看:69
本文介绍了C ++中有没有一种方法可以创建“超级私有"变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++功能的想法,我想知道是否可以创建.

I had an idea for a feature for C++, and I was wondering if it was possible to create.

假设我希望"MyClass"中的私有变量只能由两个函数(公共获取器和设置器)访问.也就是说,如果MyClass的另一个公共或私有函数试图获取或更改我的超级私有变量的值,我将得到一个编译错误.但是,getter和setter的行为正常.

Let's say I want a private variable in 'MyClass' to be accessible only by two functions, the public getter and setter. That is, if another public or private function of MyClass tries to get or change the value of my super-private variable, I will get a compile error. However, the getter and setter behave normally.

有什么想法吗?

一个用例是让getter/setter执行错误检查或其他形式的逻辑.我甚至都不希望类本身直接接触变量.

Edit 1: A use case is having the getter/setter perform error checking or other form of logic. I wouldn't want even the class itself touching the variable directly.

然后是这样的:

template <class T>
class State{
private:
    T state;

public:
    State()
    {
        state = 0;
    }

    T getState()
    {
        return state;
    }

    void setState(T state)
    {
        this->state = state;
    }
};

然后,任何类都可以继承它,并且只能通过getter/setter访问状态".当然,如果没有按照您想要的逻辑修改getter和setter的方法,该类就没有用了.

And then any class can inherit it and access 'state' only through the getter/setter. Of course, the class is useless without modifying the getter and setter according to your desired logic.

推荐答案

C ++中可访问性的粒度是该类.

The granularity of accessibility in C++ is the class.

因此,如果您需要使变量只能被两个方法访问,则需要将变量和这两个方法移动到一个单独的类中,该类专门用于维护隐私.

So if you need to make a variable accessible to only two methods you need to move the variable and the two methods into a separate class, dedicated to maintaining privacy..

这篇关于C ++中有没有一种方法可以创建“超级私有"变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆