如何修复C ++中的多个定义错误? [英] how to fix multiple definition error in c++?

查看:57
本文介绍了如何修复C ++中的多个定义错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图查看其他相关帖子,但我仍然陷入困境

I tried to look at other related posts but I'm sill stuck

我的头文件看起来像这样

My header files looks something like this

Node.hpp

      #include<iostream>
using namespace std;
#ifndef NODE_HPP
    #define NODE_HPP



        struct Node
        {
            int value;
             Node *start;
             Node *end;
        }
         *start, *end;
         int count= 0;


        #endif

Queue.hpp

Queue.hpp

  #include<iostream>
using namespace std;
#ifndef QUEUE_HPP
#define QUEUE_HPP
#include "Node.hpp"

class Queue{
    public:
        Node *nNode(int value);
        void add(int value);
        void remove();
        void display();
        void firstItem();
        Queue()
        {   
            start = NULL;
            end = NULL;
        }   
    };
    #endif

我对队列的实现类似于

#include<iostream>
using namespace std;

#include "Queue.hpp"
#include<cstdio>
#include<cstdlib>

主体看起来像

  #include<iostream>
    using namespace std;
    #include "Queue.hpp"
    #include<cstdio>
    #include<cstdlib>

我遇到以下错误

 /tmp/ccPGEDzG.o:(.bss+0x0): multiple definition of `start'
    /tmp/ccJSCU8M.o:(.bss+0x0): first defined here
    /tmp/ccPGEDzG.o:(.bss+0x8): multiple definition of `end'
    /tmp/ccJSCU8M.o:(.bss+0x8): first defined here
    /tmp/ccPGEDzG.o:(.bss+0x10): multiple definition of `count'
    /tmp/ccJSCU8M.o:(.bss+0x10): first defined here

我在做什么错了?

推荐答案

其他人已经解释了错误的原因:您正在多个转换单元中定义相同的全局变量.

Others already have explained the cause of the error: you are defining the same global variables in multiple translation units.

一种可能的解决方法是仅在一点中定义它们,并在头文件中将它们声明为 extern .

A possible fix is to define them in just one point and declare them as extern in the header file.

但是,我认为真正的问题是:您真的需要那些全局变量吗?如果要使它们成为队列对象状态的一部分,则应使它们成为实例变量.

However, in my opinion the real question is: do you really need those global variables? If they are meant to be part of the state of a queue object, we should make them instance variables.

class Queue{
    public:
        Node *nNode(int value);
        void add(int value);
        void remove();
        void display();
        void firstItem();
        Queue()
        {   
            start = NULL;
            end = NULL;
        }   
        Node *start, *end; // <----
    };

通过这种方式,我们可以在运行时使用多个队列对象,并且每个队列对象将管理自己的数据.相比之下,实例化原始类的许多对象是没有用的,因为它们都将在 same 队列上进行操作.

In this way we can use multiple queue objects at runtime, and each of them will manage its own data. By comparison, instantiating many objects of the original class is useless, since they will all operate on the same queue.

TL; DR:封装状态,避免使用全局变量.

TL;DR: encapsulate your state, avoid globals.

这篇关于如何修复C ++中的多个定义错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆