繁体   English   中英

如何访问在命名空间中声明的变量到另一个cpp文件中

[英]How to access a variable which is declare in namespace into another cpp file

螺旋测试

#ifndef SPIRALTEST_H_
#define SPIRALTEST_H_
namespace eveready
{
 struct TNotes{
  int pie;
  void meth();
 };
 extern TNotes tell;
}
#endif /* SPIRALTEST_H_ */

SpiralTest.cpp

#include "SpiralTest.h"

namespace eveready
{
void TNotes::meth(){
 pie=0;
}
}

现在我正在尝试将变量pie访问abc.cpp

abc.cpp

#include "SpiralTest.h"
using namespace eveready;
tell.meth();

但它显示错误,当我编译(的.text +×49):未定义的引用`永备::告诉”

我也尝试`永备:: tell.meth(); 但再次显示相同的错误。 我该怎么办..?

这个

extern TNotes tell;

只是名字tell的声明。 您必须在abc.cpp定义相应的对象

#include "SpiralTest.h"
using namespace eveready;

//...

TNotes tell;
//..
tell.meth();

考虑到函数调用必须位于其他函数中。 它可能不在名称空间中。

您应该重新设计该程序。 用全局变量进行意大利面条编程是不好的。 而是使用面向对象的设计(具有一致的代码格式):

螺旋测试

#ifndef SPIRALTEST_H_
#define SPIRALTEST_H_
namespace eveready
{
  class TNotes
  {
    private:
      int pie;
    public:
      void meth();
  };
}
#endif /* SPIRALTEST_H_ */

SpiralTest.cpp

#include "SpiralTest.h"

namespace eveready
{
  void TNotes::meth()
  {
    pie=0;
  }
}

abc.cpp

#include "SpiralTest.h"
#include "the_file_where_tell_variable_is_allocated.h"

using namespace eveready;

TNotes tell = some_class_in_that_other_file.get();
tell.meth();

C ++不推荐使用结构。 您在SpiralTest.h中将tell声明为extern,这意味着编译器认为它将在其他地方分配存储。 因此,当在abc.cpp中遇到tell时,链接器将引发错误。

1)使用类而不是结构。 2)在Spiraltest.cpp或abc.cpp中定义tell(也许是由TNotes类的构造函数)

无需外部命名空间的实例,这不是访问命名空间成员的正确方法。 正确的方法如下所示。

另一件事是尝试初始化pie的值,这可以使用struct TNotes的构造函数来完成

以下是更改后的文件,它们可以按预期运行。

注意:我已经添加了meth()定义来测试我的代码。

螺旋测试

#ifndef SPIRALTEST_H_
#define SPIRALTEST_H_

namespace eveready
{
  struct TNotes
  {
     int pie;
     void meth();
     TNotes(int x)
     {
        pie = x;
     }
  };
}

#endif /* SPIRALTEST_H_ */

SpiralTest.cpp

#include"SpiralTest.h"
#include<iostream>

using namespace eveready;


void TNotes::meth()
{
   std::cout<<"inside meth";
}

abc.cpp

#include "SpiralTest.h"

using namespace eveready;

int main()
{
TNotes tell(0);
tell.meth();

return 0;
}

如有任何疑问,请随时添加评论。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM