简体   繁体   English

我可以使用C ++中的指针更改静态类成员变量的值吗?

[英]Can I change the value of a static class member variable using a pointer in C++?

I'm trying to change the value of a static class member variable by returning a pointer to main via an in-class function - the script isn't working and I've tried a few different things, so I decided to reach out for some help. 我正在尝试通过类内函数返回指向main的指针来更改静态类成员变量的值-脚本无法正常工作,并且尝试了一些其他操作,因此我决定尝试一些帮助。 Any ideas, or more efficient ways to do what I'm trying to do? 有什么想法或更有效的方式来做我想做的事情吗?

#include <iostream>

using namespace std;

class container
{
public:
    int accstatint()
    {
        int *ptr=&container::statint;
        return *ptr;
    }
private:
    static int statint;
};
int container::statint=0;

int addone(int *n)
{
    return *n++;
}

int main()
{
    container obj;
    int *ptr=obj.accstatint();
    addone(*ptr);
    cout<<*ptr;
}
int accstatint()
{
    int *ptr=&container::statint;
    return *ptr;
}

This is returning a copy of the int , which means you cannot modify it. 这将返回int的副本,这意味着您无法对其进行修改。 You need to return a reference (or pointer) to the int instead: 您需要返回对int的引用(或指针):

int& getStatInt() const { return container::statint; }

If you truly want to use a pointer, you can with this (but there's no advantage and you should prefer to use a reference): 如果您确实要使用指针,可以使用它(但是没有优势,您应该更喜欢使用引用):

int* getStatIntP() { return &container::statint; }

Now you can update the integer: 现在您可以更新整数:

int main()
{
    container c;
    std::cout << c.getStatInt() << "\n"; // 0
    auto& ref = c.getStatInt();
    ref += 2;
    std::cout << c.getStatInt() << "\n"; //2
}

But all this begs the question: why do you require an object of the class to modify this? 但是所有这些都引出了一个问题:为什么您需要一个类的对象来对此进行修改? Why isn't it just public ? 为什么不只是public I mean anyone can modify it via your class anyway, so why not just allow direct access to the int to modify. 我的意思是任何人都可以通过您的类进行修改,所以为什么不直接允许直接访问int进行修改。 And if you're doing that, what is the purpose of it in the first place? 如果这样做,那么它的目的是什么? You might want to have a static int in your class to keep track of how many instances of the class are constructed, but you wouldn't allow outside access to it. 您可能希望在类中具有一个static int来跟踪构造了该类的实例的数量,但是您不允许外部访问它。 I can't help you with this without knowing what you're trying to do, you need to think about what your class is and what it does. 在不知道自己要做什么的情况下,我无法为您提供帮助,您需要考虑一下自己的班级和班级。

While a simple wrapper function would work: 虽然一个简单的包装器功能可以工作:

int& acc_staticint() { return staticint; }

You could create a getter and setter, or, since you're effectively making the variable public anyway, you could just do that and then refer to container::staticint . 您可以创建一个getter和setter,或者,由于您无论如何都有效地将变量public ,因此您可以这样做,然后引用container::staticint

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

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