简体   繁体   English

从C ++中的静态方法访问非静态类变量

[英]Accessing non-static class variable from static methods in C++

The issue with static functions is that it accepts static class variables and functions only. 静态函数的问题在于它仅接受静态类变量和函数。 A workaround is possible. 解决方法是可能的。

Class A{
int x;
static void function()
{
    A *a= new A();
    a->x; //this way we can access the non-static functions
    free(a);
    }
}

But lets assume this case in queues. 但是让我们在队列中假设这种情况。

Class A{
queue x;
static void function1()
{
    A *a= new A();
    a->x.push(some argument); //this way we can access the non-static functions
    free(a);
}

static void function2()
{
    A *a= new A();
    a->x.pop(); //this way we can access the non-static functions
    free(a);
}

} }

each function1 and function2 will create a queue of its own instance ie a, meaning queue x is different for both the functions. 每个function1和function2都会创建一个自己的实例队列,即a,这意味着两个函数的队列x不同。

How can we make the same queue accessible by both the functions with out making it static, is there a work around, please notice that function1() and function2() are running in threads parallely. 我们如何使两个函数都可以访问同一队列而又不使其变为静态,有没有变通的方法,请注意function1()和function2()在线程中并行运行。 Hence function1() is sort of independent of function2() and vice versa. 因此,function1()有点独立于function2(),反之亦然。

I think you need to review your design first why you need this. 我认为您需要首先检查您的设计,为什么需要它。

By the way, you can pass queue as an argument to the functions. 顺便说一句,您可以将队列作为参数传递给函数。 This will allow function1 and function2 to access same queue. 这将允许function1function2访问相同的队列。 However, as they are in parallel, you may need locking mechanism. 但是,由于它们是并行的,因此您可能需要锁定机制。 But queue must be created before calling function1 / function2 and they should not free it. 但是,必须在调用function1 / function2之前创建队列,并且队列不应释放它。

static void function1(A *a)
{
    a->x.push(some argument); //this way we can access the non-static functions
}

static void function2(A *a)
{
    a->x.pop(); //this way we can access the non-static functions
}

I also think that this way is not a workaround but a clean solution. 我也认为这种方式不是解决方法,而是一种干净的解决方案。

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

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