简体   繁体   English

访问范围外的变量而不传递它们?

[英]Access out of scope variables without passing them?

Is there a way to access variables outside their class? 有没有办法在类之外访问变量?

class MyClass1
{
public:
    int x;
};

class MyClass2
{
public:
    int get_x()
    {
        //somehow access MyClass1's variable x without 
        //passing it as an argument and return it.
    }
}

int main()
{
    MyClass1 obj1;
    obj1.x = 5;
    MyClass2 obj2;
    std::cout << obj2.get_x();
    return 0;
}

One of the main things making me reluctant to split my programs into many small organized classes rather than a few messy huge ones is the hassle of passing every single variable that one class might need from another. 使我不愿意将程序分为多个小型有组织的类而不是一些凌乱的大型类的主要事情之一是麻烦,因为它需要将一个类可能需要的每个变量都传递给另一个类。 Being able to access variables without having to pass them (and having to update both declarations and definitions should something change) would be very convenient and would let me code more modually. 能够访问变量而不必传递变量(必须在某些更改时必须更新声明和定义)将非常方便,这将使我进行模态编码。

Any other solutions to my issue would also be appreciated, as I suspect there may be something dangerous about trying to access variable this way. 对于我的问题的任何其他解决方案也将不胜感激,因为我怀疑尝试以这种方式访问​​变量可能会有些危险。

The only way you can get access to the x of MyClass1 is if you have an instance of that class, because x is not static . 可以访问MyClass1xMyClass1是,如果您具有该类的实例,因为x不是static

class MyClass2
{
public:
    MyClass2(MyClass1* c1) : myC1(c1) {}
    int get_x()
    {
        return myC1->x;
    }
private:
    MyClass1* myC1;
}

Then you can use this like 然后你可以像这样使用

int main()
{
    MyClass1 obj1;
    obj.x = 5;
    MyClass2 obj2{&obj1};
    std::cout << obj2.get_x();
    return 0;
}

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

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