Вопрос

I am designing a program that takes three given points and calculates the fourth to create a parallelogram. What I have so far is:

struct Parallelogram : public Polygon {
    Parallelogram(Point tl, Point tr, Point bl){
        Point br;
        int num = tr.y-tl.y;
        int denom = tr.x-tl.x;
        br.x=denom+bl.x;
        br.y=num+bl.y;
    }
};

Parallelogram::Parallelogram(Point tl, Point tr, Point bl)
{
    add(tl);
    add(tr);
    add(bl);
    add(br);
};

I get the following error when compiling:

hw6pr2.cpp:15:1: error: redefinition of âParallelogram::Parallelogram(Point, Point, Point)â
hw6pr2.cpp:6:2: error: âParallelogram::Parallelogram(Point, Point, Point)â previously defined here

My question is: If the way I am deriving from the polygon class correct? If so why am I getting this error?

Это было полезно?

Решение

You have two definitions of Parallelogram::Parallelogram(Point, Point, Point); one inside the class and one outside. You can't have multiple definitions of a function.

Assuming add adds a point to your Polygon, it seems like you really just want the second definition to be part of the first. You can define that inside your class like so:

struct Parallelogram : public Polygon {
  Parallelogram(Point tl, Point tr, Point bl) {
    Point br;
    int num = tr.y-tl.y;
    int denom = tr.x-tl.x;
    br.x=denom+bl.x;
    br.y=num+bl.y;

    add(tl);
    add(tr);
    add(bl);
    add(br);
  }
};

Alternatively, you can declare it inside your class and then define it outside:

struct Parallelogram : public Polygon {
  Parallelogram(Point tl, Point tr, Point bl);
};

Parallelogram::Parallelogram(Point tl, Point tr, Point bl) {
  Point br;
  int num = tr.y-tl.y;
  int denom = tr.x-tl.x;
  br.x=denom+bl.x;
  br.y=num+bl.y;

  add(tl);
  add(tr);
  add(bl);
  add(br);
}

Другие советы

Fix . . .

Parallelogram::AnyWordButParallelogram(Point tl, Point tr, Point bl)
{
add(tl);
add(tr);
...

If you want that code to be called on construction (as I can only guess) then . .

struct Parallelogram : public Polygon {
Parallelogram(Point tl, Point tr, Point bl){
    ...

    AnyWordButParallelogram(Point tl, Point tr, Point bl)
}

Just make sure the function is defined ahead of the constructor.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top