注册 登录
编程论坛 C++教室

新手请教个 变量赋值的问题

saeed 发布于 2019-08-11 16:51, 1886 次点击
test1.h
程序代码:

#ifndef _TEST_H                                                                 
#define _TEST_H                                                                 
                                                                        
extern int a;                                                                                                                       
                                                                        
#endif                                                                          

test1.cpp
程序代码:

#include <iostream>                                                            
#include "test1.h"                                                              
int a = 1;


test.cpp
程序代码:

#include "test1.h"                                                              
#include <iostream>                                                            
                                                                                
using namespace::std;                                                                                                                                          
a = 2;  // 如果这样写会出错, does not name a type    将这行放在 main 中赋值就没有问题,这是为什么            
int main() {                                                                    
                                                                                
    cout << a << endl;                                                         
                                                                                
}
2 回复
#2
wufuzhang2019-08-11 20:02
在全局声明区域(也就是函数定义外的区域),要给变量赋值,只能声明变量的同时初始化,
也就是说a = 2;这种行为本来就是禁止的,哪怕你换成int b; b = 2;这种赋值也是错误的,
只能int b = 2;
但是你也不能extern int a = 2;编译器会报错,因为这一句话的意思是定义外部变量并初始化,
而a你已经在其他地方定义过了,所以不能二次定义。


综上所述,你只能在函数内给外部变量赋值。
#3
saeed2019-08-11 21:10
回复 2楼 wufuzhang
感谢!
1