读书人

命名空间的有关问题链接异常

发布时间: 2013-08-16 14:29:57 作者: rapoo

命名空间的问题,链接错误
为甚么我在命名空间里定义那两个变量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;

[解决办法]
引用:
Quote: 引用:

不要在头文件中定义变量。

//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 int b = 0;
这种可以加在.h文件,但是你在别的文件中用不了 (算个例外吧,暂且)
没这个关键字的,放在.cpp中定义,如6L

[解决办法]
加 static 或者 const应该都可以的吧
(我这边在vs2010下是可以的)
[解决办法]
引用:
但是我觉得不加也应该可以的啊,可他就是有错,你试试不加static 、const能行吗,我这没vs

加了应该是可以的 前段日子回复过一个差不多的帖子,试过vs和gcc的编译器


这个也可以改,刚测好了

方案一、
a.cpp 和 b.cpp的 using namespace test;
改成 namespace test { ...... }


方案二、 按你这里写的用using namespace test; 然后 int test::p = 1; 加个test::作用域修饰符



我的实现文件从来不用using namespace MY_NAMESPACE; 都是用namespace MY_NAMESPACE { ... }
不管.h 还是 .cpp 都这么用好一些

[解决办法]
int test::p = 1; 可以放到main.cpp,如果main.cpp中有这一句,那么
此时,a.cpp和b.cpp中不能有 "int test::p = 1; ","int test::p;"
你可以不什么都不写(p相关的),但应该也可以extern int test::p; (没试过)


不加test::有问题,是因为编译器把a.cpp中的 int p = 1; 当成 int ::p = 1;了

你查下extern关键字的含义与用法
自己也试试p放在不同的文件中,怎么写才可以,多实践


问题肯定不会等到运行期的, 要么编译错误,要么链接错误
(编译不行,却能运行,说明运行的是之前编译的文件,你没清理掉,那么重新编译)
------解决方案--------------------


引用:
为什么不能写成
using namespace test;
int q = 1;


using namespace test只是把test内的标示符在这里可见,不表示下面的语句要被包含在test中。
否则

#include <string>
using namestpace std;

int main()
{
return 0;
}
假设main被包含在std中了,这个程序就无法编译了(因为链接需global名字空间中的main)

读书人网 >C++

热点推荐