c++ - 如何使用全局用户定义类对象

标签 c++

在 Friend.h 中

#ifndef FRIEND
#define FRIEND 
class Friend
{

public:
    static int i ;
    int j;
    Friend(void);
    ~Friend(void);
}frnd1;
#endif

在 Friend.cpp 中

#include "Friend.h"
int Friend::i = 9;
extern Friend frnd1;
Friend::Friend(void)
{
}

Friend::~Friend(void)
{
}

在 main.cpp 中

#include <iostream>
using namespace std;
#include"Friend.h"

int main()
{
frnd1.j = 9;
cout<<"hello";
getchar();
return 0;
}

当我运行上面的代码时,它给出了以下链接器错误:

error LNK2005: "class Friend frnd1" (?frnd1@@3VFriend@@A) already defined in main.obj

我无法理解如何在 main 函数中使用全局对象。

最佳答案

问题是 frnd1在头文件中定义,因此最终在每个翻译单元中实例化。

你要做的是在头文件中声明,然后在相应的.cpp定义文件:

  1. 更改 class Friend { ... } frnd1;class Friend { ... };Friend.h .
  2. 添加extern Friend frnd1;Friend.h ;
  3. 更改 extern Friend frnd1;Friend frnd1;Friend.cpp .

friend .h:

class Friend
{
  ...
};

extern Friend frnd1;

friend .cpp:

#include "Friend.h"

Friend frnd1;

关于c++ - 如何使用全局用户定义类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13564360/

相关文章:

c++ - 当函数未在默认返回路径上显式返回值时强制出错?

c++ - 在c++中的macOS Catalina上编译 header 和cpp文件的问题

java - 我无法从 C++ 程序运行可执行 jar

c++ - 在类中使用时,[this] 和 [&] 在 lambda 捕获列表中是否等效?

c++ - 使用 bool operator== 比较对象

c++ - 将内存复制到结构时出现 EXC_BAD_ACCESS

c++ - 使用分配器 Hook 时如何检索被释放的字节?

c++ - 获取错误 : 'mutex' in namespace 'std' does not name a type in MinGW mysys prompt

c++ - 运算符<和严格的弱排序

c++ - 根据另一个对象和概率随机选择一个对象?