繁体   English   中英

从 static 方法访问 class 的私有成员变量

[英]Accessing private member variables of a class from a static method

我可以使用 object 实例(指向对象的指针)直接访问下面代码中显示的 class 的私有成员变量。 据我了解,私人成员不应该被访问。 有人可以帮忙解释这种行为背后的原因吗?

#include <iostream>

class myClass;
using myClassPtr = std::shared_ptr<myClass>;

class myClass {
public:
    myClass(unsigned int val) : m_val(val) {}
    ~myClass() {}

    static
    myClassPtr create(unsigned int val) {
        myClassPtr objPtr = nullptr;
        objPtr = std::make_shared<myClass>(val);
        if(objPtr) {
            std::cout << objPtr->m_val << std::endl;
        }
        return objPtr;
    }
private:
    unsigned int m_val;
};

int main () {
    myClassPtr objPtr = myClass::create(10);
    return 0;
}

Output

anandkrishnr@anandkrishnr-mbp cpp % g++ static_test.cc -std=c++11 -Wall -Werror
anandkrishnr@anandkrishnr-mbp cpp % ./a.out
10
static myClassPtr create(unsigned int val) {

create()myClass的 static 方法,它是此 class 的成员。 因此,它有权访问其 class 的所有私有成员和方法。 此权利不仅延伸到它自己的 class 实例,而且延伸到此 class 的任何实例。

据我了解,私人成员不应该被访问。

...除了他们的 class 的成员。

让我们为您的 class 创建一个完全没有意义的复制构造函数,与默认情况下获得的复制构造函数相同:

myClass(const myClass &o) : m_val{o.m_val} {}

此复制构造函数在访问传入的m_val的 m_val 时没有任何问题。 完全相同的事情发生在这里。 m_val是其 class 的私有成员。 It doesn't mean that only an instance of the same exact object can access its private members, it means that any instance of the class, or a static class method, can access the private class members.

class 上的访问修饰符的性质是限制在该 class之外使用类的成员。

由于create()myClass中,因此create()可以访问您声明的myclass的任何私有成员(或实际上任何成员)。 包括m_val

例如,让我们做一个简单的 class,

如果你有代码:

class box {
private:
    int width;
    int height;
};
int main() {
    box b;
    b.width;

    return 0;
}

编译器会抛出错误: error C2248: 'box::width': cannot access private member declared in class 'box'

Because the main() function is declared outside of the class, therefore, the main() function is not allowed to access private members of the class box .

如果我们想访问 class 之外的宽度,比如宽度,我们需要将这些成员公开,以允许程序中的其他所有内容看到这些成员:

class box {
private:
    int width;
    int height;
public:
    int pubWidth;
    int pubHeight;
};
int main() {
    box b;
    b.pubWidth;

    return 0;
}

这一次,我们试图访问的成员是公共的,( pubWidth ) 允许外部函数、类等访问这些box成员

Programiz 在我看来,有一篇关于 c++ 中访问修饰符的好文章,易于理解。 我建议看看。 链接在这里

小提示:如果没有指定,class 中的所有成员都是私有的,除了构造函数、析构函数,也许还有一些我想不出的特殊用例。

希望这能解决问题!

暂无
暂无

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

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