开发者

Using protected static variable in another file

开发者 https://www.devze.com 2023-04-11 08:12 出处:网络
How can I access a variable that has been declared as static and protected in a class definition开发者_开发问答for use in another file b.cppThe only code allowed to use protected class members (static

How can I access a variable that has been declared as static and protected in a class definition 开发者_开发问答for use in another file b.cpp


The only code allowed to use protected class members (static or not) are explicit friends of the class in question and classes derived from the class in question (and of course, members of the class itself). Therefore, if "you" want to access that value, then "you" must either be a friend of that class or a member of a class derived from it.

The protection classes (public, protected, and private) exist to provide protection for data. By declaring the member to be protected, the writer of that class is making a semi-strong statement about what code should be allowed to touch that piece of memory. If you're not a derived class or have been given permission with an explicit friend specification, then you're not allowed to touch it.

You should not derive from a class solely to get access to a protected static member. You should only derive from a class if it makes sense to do so based on what your derived class is trying to do.


Having declared as protected, the static variable can only be accessed with in it's member functions and it's derived classes( public, protected inheritance ).


I faced this once in a class that I can't modify(standard adaptors), and came up with the following solution with the help of SO & Google!

#include <iostream>

class my_type{
protected:
    static int var;
};

int my_type::var = 0;

int& get_var(my_type& obj){
    class protected_accessor : my_type{
    public:
        static int& get_var(my_type&){
            return my_type::var;
        }
    };
    return protected_accessor::get_var(obj);
}

int main(){
    my_type obj;
    std::cout << get_var(obj) << std::endl;
    get_var(obj) = 1;
    std::cout << get_var(obj);
}

I have used a variation of this code in my tiny utility: https://bitbucket.org/AraK/streamer/wiki/Developer_FAQ. Look for "Streaming Standard Adapters".

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号