【问题标题】:Redefinition of Class after Separating to .h/.cpp分离到 .h/.cpp 后重新定义类
【发布时间】:2013-06-19 15:09:55
【问题描述】:

我知道这是一个关于 C++ 的常见问题,但按照其他答案等的建议,我仍然无法让我看似简单的代码工作。我的问题是下面的代码给出了“错误:'class Communicator'的重新定义”:

global.h

#ifndef GLOBAL_H 
#define GLOBAL_H

class object_payload;
class pending_frame;

class Communicator {
private:
    map<string,object_payload*> local_objects;
    map<string,pending_frame*> remote_tasks;
    bool listening;

public:
    Communicator();
    void stop_listening();
    void add_to_remote_tasks(string name, pending_frame* pfr);
    void listen();
    void distributed_release(string task_name);

};

extern Communicator communicator;

#endif

global.cpp

#include "global.h"

class Communicator {

private:
    map<string,object_payload*> local_objects;
    map<string,pending_frame*> remote_tasks;

    bool listening;

public:

    Communicator(){
        // implementation
    }

    void stop_listening(){
        // implementation
    }

    void add_to_remote_tasks(string name, pending_frame* pfr){
        // implementation
    }

    void listen(){
        // implementation
    }

    void distributed_release(string task_name){
        // implementation
    }
};

Communicator communicator;

有谁知道为什么会出现这个错误? .cpp 包含标头。我还有其他 .cpp 文件也包含标头,但是对于守卫,我不明白为什么这很重要。

感谢您对此的任何帮助,非常感谢。

编辑:另外,我的 runner.cpp 文件(带有 main)包含 global.h 以便访问通信器全局对象。

【问题讨论】:

  • 您的标题显示“类 Communicator”,您的 cpp 文件显示“类 Communicator”,而您的错误显示“重新定义‘类 Communicator’”。这很公平。

标签: c++ redefinition


【解决方案1】:

你必须只有一个类的定义。目前您从#include 获得一个,另一个在文件中。

你不能重复类本身,只是实现类外的功能,比如

Communicator::Communicator(){
    // implementation
}

【讨论】:

  • 啊,是的,我知道现在是如何进行分离的了。感谢您和其他(非常快速的)贡献者。
【解决方案2】:

这不是你进行分离的方式。 class(即声明)进入标题; CPP 文件应该有方法实现,如下所示:

Communicator::Communicator() {
    ...
}
void Communicator::stop_listening() { 
    ...
}

等等。注意完全限定名称的 Communicator:: 部分:这是告诉编译器您定义的函数属于 Communicator 类的原因。

【讨论】:

    【解决方案3】:

    在您的 cpp 文件中,您只需定义已声明但未在标头中定义的函数,并将它们的范围限定为您的类:

    Communicator::Communicator(){
        // implementation
    }
    
    void Communicator::stop_listening(){
        // implementation
    }
    
    void Communicator::add_to_remote_tasks(string name, pending_frame* pfr){
        // implementation
    }
    
    void Communicator::listen(){
        // implementation
    }
    
    void Communicator::distributed_release(string task_name){
        // implementation
    }
    

    【讨论】:

      【解决方案4】:

      您在头文件中定义类Communicator,然后尝试在.cpp 文件中添加它。你不能在 C++ 中这样做——类定义的所有部分都必须在同一个地方。

      您的头文件可能应该包含所有成员定义和函数声明,并且您的 .cpp 应该继续定义成员函数,例如:

      void Communicator::stop_listening() { ... }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-20
        相关资源
        最近更新 更多