繁体   English   中英

C ++中的错误:类构造函数的重新定义

[英]Error in C++ : redefinition of class constructor

我在尝试编译时遇到了这两个错误。

有人知道怎么了吗?

在想也许我#include错误的头文件? 代码示例和错误如下:

错误:

Square.cpp:8: error: redefinition of ‘Square::Square(bool, Point*, std::string, int)’
Square.h:21: error: ‘Square::Square(bool, Point*, std::string, int)’ previously defined here
Square.cpp: In member function ‘Point Square::getCoord()’:
Square.cpp:22: error: expected primary-expression before ‘]’ token
Square.cpp: In member function ‘void Square::setCoord(Point*)’:
Square.cpp:32: error: expected primary-expression before ‘]’ token
Square.cpp:32: error: expected primary-expression before ‘]’ token

cpp文件

#include "Square.h"`
#include <cmath>
using namespace std;

Square::Square(bool containsWarpSpace, Point coord[], string shapeName, int vertPoint):ShapeTwoD(shapeName, containsWarpSpace) {

 vertPoint = vertPoint;
 coord[] = coord[];

}

int Square::getVertPoint()
{
    return vertPoint;
}

Point Square::getCoord()
{
    return coord[];
}

void Square::setVertPoint(int verticleP)
{
    vertPoint = verticleP;
}

void Square::setCoord(Point coord[])
{
    coord[] = coord[];
}

标题:

#include "ShapeTwoD.h"

class Square : public ShapeTwoD
{
    private:
        int vertPoint;
        Point coord[];

    public:
        //Accessor
        int getVertPoint();
        Point getCoord();

        //Mutator
        void setVertPoint(int vertP);
        void setCoord(Point coord[]);

        //virtual member
        virtual double computeArea(Point x, Point y);

        Square(bool containsWarpSpace, Point coord[], std::string shapeName = "Square", int vertPoint = 4):ShapeTwoD(shapeName, containsWarpSpace){}

};

您将定义构造函数两次,一次在标题中,一次在实现文件中。 在标题中,您只需要这样声明:

Square(bool containsWarpSpace,
       Point coord[],
       std::string shapeName = "Square",
       int vertPoint = 4);

您还需要修复对coord的处理,例如将coord更改为

Point* coord;

和使用

Point* Square::getCoord()
{
    return coord;
}

this->coord = coord;

在构造函数和setCoord()

请注意,您的coord处理方式对我来说似乎很奇怪而且很危险,但是如果您没有进一步了解您实际上在做什么的信息,就很难给出具体的建议。 通常,考虑在手动内存/阵列管理上使用标准容器。

编译器清楚地告诉您问题所在:
您两次在头文件中定义了构造函数,一次在cpp文件中定义了构造函数。

另外,您打算做什么?

coord[] = coord[];

您应该了解所编写的每个代码语句。 想一想,您打算将此语句做什么? 然后将其与您所学的语言语法相匹配。

源文件:

Square::Square(bool containsWarpSpace, Point coord[],
               string shapeName, int vertPoint)
   :ShapeTwoD(shapeName, containsWarpSpace)
{
    vertPoint = vertPoint;
    coord[] = coord[];
}

头文件:

Square(bool containsWarpSpace, Point coord[], 
       std::string shapeName = "Square", int vertPoint = 4)
    :ShapeTwoD(shapeName, containsWarpSpace)
{}

看起来像是同一功能的两个不同版本。
头文件中的那个调用基类构造函数,但构造函数的主体中没有任何代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM