c – 未定义的参考::
发布时间:2020-12-16 09:41:09 所属栏目:百科 来源:网络整理
导读:我正在研究一些代码来标记何时对网站进行了更改.我在类中使用静态变量时遇到了问题,因此我想在命名空间中声明一个变量,并在进行更改时设置此== 1. 以下是我编写的一些简化代码来表示问题: p.h: #includeiostreamusing namespace std;#ifndef p_H#define p_
我正在研究一些代码来标记何时对网站进行了更改.我在类中使用静态变量时遇到了问题,因此我想在命名空间中声明一个变量,并在进行更改时设置此== 1.
以下是我编写的一些简化代码来表示问题: p.h: #include<iostream> using namespace std; #ifndef p_H #define p_H namespace testing{ extern int changes_made; class p { public: void changed(); void print_change(); void print_change_ns(); private: static int changes; int info; }; } #endif p.cpp: #include "p.h" #include<iostream> using namespace testing; int p::changes=0; void p::changed(){ p::changes=1; } void p::print_change(){ cout << p::changes << endl; } void p::print_change_ns(){ if (testing::changes_made == 1){ cout << 1 << endl; } else{ cout << 0 << endl; } } main.cpp中: #include<iostream> #include"p.h" using namespace std; using namespace testing; int main(){ p test1,test2,test3; test3.changed(); changes_made=1; cout << "test1 "; test1.print_change(); test1.print_change_ns(); cout << "test2 "; test2.print_change(); test2.print_change_ns(); cout << "test3 "; test3.print_change(); test3.print_change_ns(); p test4; cout << "test4 "; test4.print_change(); test4.print_change_ns(); return 0; } 我收到以下错误消息: p.o: In function `testing::p::print_change_ns()': p.cpp:(.text+0x45): undefined reference to `testing::changes_made' main.o: In function `main': main.cpp:(.text+0x9b): undefined reference to `testing::changes_made' collect2: ld returned 1 exit status 任何有关这方面的帮助将不胜感激.我之前有多个声明错误,所以我介绍了#ifndef的东西,以及变量之前的extern. 解决方法
外部变量,如extern int changes_made;需要在某处创建存储空间.你所说的是“在链接阶段,你会发现有人会向你输出这个int类型名称的符号”.
然后你没有完成承诺,因为没有单位导出int testing :: changes_made. 在一些.cpp文件中,您要链接上面的p.cpp和main.cpp(甚至可能是p.cpp),创建一个变量的实例,如下所示: namespace testing { int changes_made = 0; } 并且您的链接器错误应该消失. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ajax+php $.post()中文乱码解决办法(utf-8 ---> gb2312)
- 还在找react例子? 记录一下react练习小心得
- 如何在C++中实现按位存取
- ios – 在Xcode版本4.5.2(4G2008a)捆绑包中找不到OpenGL ES
- hdu 6140 Hybrid Crystals 阅读题 OR bitset 优化01背包
- 为什么Swift在将可选String转换为UnsafePointer时返回一个意
- c#通过unicode编码判断字符是否为中文示例分享
- cocos2d-x 3.4 eclipse android 编译是出现WindowsError: [
- 当容器遇上数据库……
- 几个在线画图工具