命名空间的问题,链接错误
为甚么我在命名空间里定义那两个变量p、q就会出现链接错误呢?
//classA.h
#ifndef __hji__classA__
#define __hji__classA__
#include "classB.h"
namespace test
{
class classB;
//int q = 1;
class classA
{
public:
classA();
int a;
int m(int);
};
};
#endif /* defined(__hji__classA__) */
//classB.h
#ifndef __hji__classB__
#define __hji__classB__
#include "classA.h"
namespace test
{
class classA;
//int p = 23;
class classB
{
public:
classB();
int b;
int plus(int);
};
};
#endif /* defined(__hji__classB__) */
//classA.cpp
#include "classA.h"
using namespace test;
classA::classA()
{
a = 2;
}
int classA::m(int num1)
{
classB cb;
return num1+cb.b;
}
//classB.cpp
#include "classB.h"
using namespace test;
classB::classB()
{
b = 3;
}
int classB::plus(int num1)
{
classA *ca = new classA;
return num1+ca->a;
}
命名空间 连接错误
//main.cpp
#include<iostream>
#include "classA.h"
#include "classB.h"
using namespace test;
int main()
{
int e = q+p;
std::cout<<e<<std::endl;
}
[解决办法]
namespace后面是没;的
[解决办法]
不要在头文件中定义变量。
//A.h
//int q = 1;
extern int q;
//A.cpp
int q = 1;
//A.cpp要写成这样
namespace test
{
int q = 1;
}
//能写成
using namespace test;
int q = 1;
但是我觉得不加也应该可以的啊,可他就是有错,你试试不加static 、const能行吗,我这没vs
为什么不能写成using namespace test;
int q = 1;
假设main被包含在std中了,这个程序就无法编译了(因为链接需global名字空间中的main)
#include <string>
using namestpace std;
int main()
{
return 0;
}