非成员,非静态变量和方法的范围

时间:2012-03-06 12:02:48

标签: c++ scope

Test.h

class Test
{
public:
    Test();
    //some methods
private:
    int var;
    //some vars
}

Test.cpp的

#include "Test.h"
int a;

void func()
{
     //some code here
}
Test::Test()
{
     //some code
}     

变量a和函数func()是非成员且非静态的。

变量a和函数func()的生命周期是什么?

将Test类视为共享库的一部分。该库的其他类可以通过解析运算符访问afunc()吗?

变量a / func()的静态声明与a / func()的非静态声明之间有什么区别?

5 个答案:

答案 0 :(得分:2)

变量和函数具有相同的范围:它们从它们的声明点开始存在。

这与类的属性和方法相比有所不同,类的范围仅限于类本身,而且顺序较少(尽管可能......对于类型)。

答案 1 :(得分:1)

变量a是一个全局变量,其范围是整个程序运行时,即它在程序启动期间创建并在程序退出期间销毁。 func是一个全局函数,函数没有任何附加范围的概念。

答案 2 :(得分:1)

变量“a”是Test.cpp的全局变量 和“func”是Test.cpp中的正常函数。 编辑部分: - 但你可以使用相同的变量&不同地方的方法如果你做的如下所示。

//file1.h
#ifndef FILE1_H
#define FILE1_H
extern int a;
extern void func();
#endif    
//end of file1.h

//file1.cpp
#include"file1.h"    
int a; // a=0 as it is global variable
static int x = 10;// Scope is limited, it can only be used in file1.cpp

static void func2(){ 
    int z = x;
    z = x+z;
    //... some thing u r doing    
} 
void func(){
    //... some thing u r doing    
}      
//end of file1.cpp


//file2.cpp
#include"file1.h"
//U can use variable "a" & method "func" defined in file1.cpp . For an eg:-    
int add(int b){
    func();//func defined in file1.cpp but used here
    //func2(); //It will throw error if you remove the comment before func2 method as 
               //the scope of func2 is limited to file1.cpp as it is static method
    return a+b;// a defined in file1.cpp but used here
}    
int main(){    
    //some code exists here
    return 0;
}

//end of file2.cpp
//================

你可以玩很多东西。这只是其中一个例子。 就像声明静态全局变量一样,该变量的范围仅限于该文件。

变量“a”& “func”可由存在于Test Class所在的同一文件中的其他类访问。​​

如果您将任何变量或方法声明为静态全局变量,那么该变量的范围&方法仅限于该文件,如上例所述。

答案 3 :(得分:1)

在C ++中,由C ++11§3.3.1/ 1定义的范围是一个(可能是不连续的)文本区域,其中可以使用名称没有资格提及同一实体。

潜在范围是当潜在范围内没有相同名称的声明时名称将具有的范围。

变量名称和函数名称的范围从声明扩展到文件末尾。

答案 4 :(得分:1)

MSDN页面是您问题的答案。它定义了范围和生命周期。

a在整个文件中具有范围和生命周期。

func()没有范围或生命周期。他们只有可见度。

如果共享库的一部分也起作用,并且其他部分可以访问全局变量,则提供的库是可见的。

在这种情况下,静态并没有多大区别。但是静态的局部变量获得全局范围,但只有本地可见性。

相关问题