[英]My non-member static function allows changing and creating of non static variables
this is the code snippet 这是代码片段
static chck()//tracking how many times main has been called
{
static a=0;
int y=0;//this is not supposed to work
cout<<"Total time main has been called: ";
a++;
return a;
}
our teacher told us that static functions can't change or create non static variables but it works for me ,why? 我们的老师告诉我们,静态函数无法更改或创建非静态变量,但对我有用,为什么?
In this case "y" is a stack variable which this function can access. 在这种情况下,“ y”是此函数可以访问的堆栈变量。
The theory is static member functions (static Methods in a class) cannot access non static member variables (non static variables in the class) as there is no object as "this" inside a static member function. 理论上是静态成员函数(类中的静态方法)无法访问非静态成员变量(类中的非静态变量),因为在静态成员函数中没有“ this”这样的对象。
static
may well be the most overused keyword in c++. static
可能是c ++中使用最多的关键字。 Your first use of it refers to the linkage of chck()
, ie it has internal linkage. 第一次使用它是指
chck()
的链接,即它具有内部链接。 Your second use makes a
static
with respect to calls to ckch()
, ie it's value will be preserved between calls. 您的第二次使用使对
ckch()
调用a
static
,即它的值将在ckch()
调用之间保留。 You are think of static
member functions of a class
that can't access non- static
data members, ie those data members that are created per object instance. 您想到的是不能访问非
static
数据成员的class
的static
成员函数,即,每个对象实例创建的数据成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.