首页 > 解决方案 > C++抽象基类的重新定义

问题描述

使用派生类可以构建的构造函数实现抽象基类。我在编译代码时遇到问题,我提前为使用命名空间 std 表示歉意;这是我的任务所必需的。

我尝试了 headerguards 并检查了我的包含代码。我将这些文件分成一个主文件(Assn2)、抽象基类(S2D).h 和 .cpp 文件。

在主文件 Assn2 中

#include <iostream>
#include <string>
#include <fstream>
#include "S2D.h"

在 S2D.h 内

#ifndef _S2D_H_
#define _S2D_H_
#include <iostream>
#include <string>
using namespace std;

class ShapeTwoD {

    private:
        string name;
        bool containsWarpSpace;

    public: 
        ShapeTwoD();
        ShapeTwoD(string, bool);

在 S2D.cpp 内

#include <iostream>
#include <string>
#include "S2D.h"

using namespace std;

class ShapeTwoD {
    ShapeTwoD::ShapeTwoD() {
        name = " ";
        containsWarpSpace = false;
    }

    ShapeTwoD::ShapeTwoD(string Name, bool ContainsWarpSpace) {
        name = Name;
        containsWarpSpace = containsWarpSpace;
    }

};

这是我收到的错误。

S2D.cpp:7:7: error: redefinition of ‘class ShapeTwoD’
 class ShapeTwoD {
       ^~~~~~~~~

In file included from S2D.cpp:3:
S2D.h:7:7: note: previous definition of ‘class ShapeTwoD’
 class ShapeTwoD {
       ^~~~~~~~~
make: *** [S2D.o] Error 1

只是一个后续问题,我正在尝试基于这个抽象基类实现派生类。我正在尝试基于这些抽象构造函数创建具有更多参数的派生类构造函数。

例如。

Rectangle::Rectangle(string Name, bool ContainsWarpSpace, int YSize, int XSize, int(*ArrY), int (*ArrX) )

我想知道我在 Java 中学到的这个概念是否适用于 C++?

标签: c++c++11

解决方案


在 S2D.cpp 内

#include <iostream>
#include <string>
#include "S2D.h"

using namespace std;
class ShapeTwoD { // 删除这一行
   ShapeTwoD::ShapeTwoD() {
        name = " ";
        containsWarpSpace = false;
    }

    ShapeTwoD::ShapeTwoD(string Name, bool ContainsWarpSpace) {
        name = Name;
        containsWarpSpace = containsWarpSpace;
    }
}; // 删除这一行

推荐阅读