【问题标题】:error C2011: 'class type redefinition - Basic Inheritance错误 C2011: '类类型重新定义 - 基本继承
【发布时间】:2016-10-12 19:00:50
【问题描述】:

以下是 4 节课,我正在学习基本的 c++ 语法,男孩是不是比我用过的其他语言更难,更不宽容。我有一个主类,基类“BaseArray”和两个子类“OrderedArray”和“UnorderedArray”。

Main.cpp

#include <iostream>
#include "OrderedArray.cpp"
#include "UnorderedArray.cpp"

using namespace std;

int main() {


    system("PAUSE");
    return 0;
}

BaseArray.cpp

#include <iostream>

using namespace std;

class BaseArray {
    public:
        BaseArray::BaseArray() {

        }
};

OrderedArray.cpp

#include <iostream>
#include "BaseArray.cpp"

using namespace std;

class OrderedArray : public BaseArray {
    OrderedArray::OrderedArray() {

    }
};

UnorderedArray.cpp

#include <iostream>
#include "BaseArray.cpp"

using namespace std;

class UnorderedArray : public BaseArray {
    UnorderedArray::UnorderedArray() {

    }
};

我收到的错误如下,来自在线搜索其他线程。我认为这可能与重复调用类有关。老实说,我不知道。如果有人能指出我正确的方向,那就太好了,在此先感谢!

error C2011: 'BaseArray':'class' type redefinition
error C2504: 'BaseArray':base class undefined

要修复此错误,我可以删除 main.cpp 顶部的包含之一,但我需要这些来创建对象并稍后从子类调用函数。

【问题讨论】:

  • 你需要使用include保护。
  • 几乎不应该包含 cpp 文件。您需要将代码移动到头文件中或将接口与实现分开。
  • This 基本上回答了这个问题,但我不会称之为欺骗
  • 有趣的是,我很快就阅读了头文件。现在我的问题是如何在头文件中显示继承语法?相反,拥有相同设置但包含头文件的正确方法是什么?
  • 关键是:从实现中分离接口接口在头文件中,实现在源文件中。跨度>

标签: c++ inheritance compiler-errors


【解决方案1】:

您应该将基本数组放在标题中:

BaseArray.h

#ifndef BASEARRAY_H_GUARD       // include guard
#define BASEARRAY_H_GUARD       // include guard  

                                // no using namespace !! 
                                // only includes needed for what's in the header
class BaseArray {
    public:
        BaseArray(); 
};

#endif                      // include guard

然后在 cpp 中只保留你的类的实现部分:

BaseArray.cpp

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

using namespace std;

BaseArray::BaseArray() {     // no need class enclosing: the BaseArray:: prefix is sufficient
}

您可以将相同的原则应用于派生类:

OrderedArray.h

#ifndef BASEARRAY_H_GUARD       // include guard
#define BASEARRAY_H_GUARD       // include guard  

#include "BaseArray.h"         // include only those that you need but all those that you need 

class OrderedArray : public BaseArray {   // requires BaseArray 
    OrderedArray(); 
};

#endif

OrderedArray.cpp

#include <iostream>         // include headers that are needed for class implementation   
#include "OrderedArray.h"   // this should be self contained and provide
                            // evertyhing that is needed for the class itself

using namespace std;

OrderedArray::OrderedArray() {
}

然后您必须对 UnorderedArray 执行相同的操作,最后,您必须调整 main.cpp 以包含 .h 而不是 .cpp。你完成了。

最后一点:您的 cpp 源代码文件现在可以单独编译了。这意味着您不能再仅编译 main.cpp,希望它包含所有代码:您现在必须编译 4 个 cpp 文件并将它们链接在一起。

【讨论】:

    猜你喜欢
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多