【发布时间】:2015-02-18 00:57:05
【问题描述】:
静态函数的问题在于它只接受静态类变量和函数。一种解决方法是可能的。
Class A{
int x;
static void function()
{
A *a= new A();
a->x; //this way we can access the non-static functions
free(a);
}
}
但是让我们在队列中假设这种情况。
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);
}
}
每个 function1 和 function2 将创建一个自己的实例队列,即 a,这意味着队列 x 对于两个函数是不同的。
我们如何在不使其成为静态的情况下使两个函数都可以访问同一个队列,是否有解决方法,请注意 function1() 和 function2() 在线程中并行运行。因此 function1() 有点独立于 function2() ,反之亦然。
【问题讨论】:
-
为什么需要
without making it static?或者,为什么functdion1和function2需要是静态的? -
我不知道静态要求,但有人告诉我。 function1 和 function2 需要是静态的,因为它们在 .h 和 .cpp 实现中的单独的 pthread_create 函数中传递。
-
除了提出和回答的实际问题之外,您真的不应该将
a = new A()与free(a)混为一谈。如果你new某事,delete它。如果你malloc()某事,free()它。 -
pthread_create期望一个指向采用void*的函数的指针,并且还接受一个传递给所述函数的void*参数。一种典型的方法是在那里传递this:您的function1和function2将有一个A*指针可以使用。正如所写,没有参数,它们无论如何都不适合pthread_create。 -
@IgorTandetnik 你的意思是像 function1(A a) 但是当我这样做时 pthread_create() 参数需要 function1(void),并给出一个转换错误,任何想法?
标签: c++ static static-methods static-variables