非静态与静态函数和变量 [英] non-static vs. static function and variable
问题描述
我有一个关于静态和非静态函数和变量的问题。
I have one question about static and non-static function and variable.
1)非静态函数访问静态变量。
1) non-static function access static variable.
没关系。
class Bar
{
public:
static int i;
void nonStaticFunction() {
Bar::i = 10;
}
};
int Bar::i=0;
2)非静态函数访问非静态变量
2) non-static function access non-static variable
当然OK!
3)静态函数访问静态变量& funciton
3) static function access static variable&funciton
4)静态函数访问非静态函数
4) static function access non-static function
没关系
class Bar
{
public:
static void staticFunction( const Bar & bar)
{
bar.memberFunction();
}
void memberFunction() const
{
}
}
5)静态函数访问非静态变量
5) static function access non-static variable
还是不行?我对此感到困惑。
It's OK or not OK? I am puzzled about this!
此示例如何
class Bar
{
public:
static void staticFunction( Bar & bar)
{
bar.memberFunction();
}
void memberFunction()
{
i = 0;
}
int i;
};
推荐答案
-static
变量
static function access non-static variable
没关系吗?我对这个
感到困惑!
It's OK or not OK? I am puzzled about this!
调用时,静态函数不绑定到类的实例。类实例(对象)将是保存非静态变量的实体。因此,从静态函数,你将无法访问它们,而不实际传递或存储在其他地方的特定实例进行操作。
When called, a static function isn't bound to an instance of the class. Class instances (objects) are going to be the entities that hold the "non-static" variables. Therefore, from the static function, you won't be able to access them without actually being passed or storing elsewhere a specific instance to operate on.
是的,你最后一个例子中的代码是有效的,因为你是在一个实例中传递的。但是,你不能这样做:
So yes, the code in your last example is valid, because you are passed in an instance. However, you could not do:
static void staticFunction()
{
// error, this function is static, and is therefore
// not bound to a specific instance when called
i = 5;
}
这篇关于非静态与静态函数和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!