我遇到的问题与http://www.cplusplus.com/forum/beginner/12458/上的 'greentype'提到的问题基本相同
我通过名称空间共享变量,当我尝试将函数定义放入单独的文件时出现问题.
考虑以下示例,其中我想将主代码中定义的变量'i'传递给函数a():
*nn.h:*
#ifndef _NN_H_
#define _NN_H_
namespace nn {
int i;
}
#endif
Run Code Online (Sandbox Code Playgroud)
*main.cpp*
#include <iostream>
#include "nn.h"
using namespace std;
using namespace nn;
void a();
int main()
{
i=5;
a();
}
void a()
{
using namespace std;
using namespace nn;
i++;
cout << "i = " << i << endl;
}
Run Code Online (Sandbox Code Playgroud)
但是现在如果我把a()的定义放到一个单独的文件中......
*a.cpp*
#include <iostream>
#include "nn.h"
void a()
{
using namespace std;
using namespace nn;
i++;
cout << "i = " << i << …Run Code Online (Sandbox Code Playgroud)