问题
i'm working on an exercise at uni and every time i try to compile the main.cpp i got always the same error.
actor.h:
class Actor {
public:
Actor();
Actor(double x0, double y0);
void move();
double pos_x();
double pos_y();
static const int ARENA_W = 500;
static const int ARENA_H = 500;
};
plane.h (subclass of actor):
class Plane:Actor
{
public:
Plane();
Plane(double x0, double y0);
void move();
double pos_x();
double pos_y();
//int dx = 5;
static const int W = 50;
static const int H = 20;
private:
double x, y;
};
plane.cpp
#include "plane.h"
#include "actor.h"
Plane::Plane(double x0, double y0)
{
this ->x = x0;
this ->y = y0;
//this -> dx;
}
void Plane::move()
{
x = x + 2.5 ;
}
double Plane::pos_x()
{
return x;
}
double Plane::pos_y()
{
return y;
}
main.cpp
include "plane.h"
include"actor.h"
using namespace std;
int main(int argc, char *argv[])
{
Plane plane1(25.0, 5.0);
plane1.move();
double x = plane1.pos_x();
double y = plane1.pos_y();
cout << x << " , " << y<<endl;
}
i saw there are many questions about this problem but i didn't fix it. can you help me please()? thank you
回答1:
You've declared a class Actor
in actor.h
:
class Actor {
public: Actor();
};
This means that you're going to write some code that will define this construction. This would typically end up in an Actor.cpp
file.
If you attempt to construct an Actor
without having this implementation, you will get an error from the linker because you're missing the default constructor.
Now you've declared a Plane
that's a subclass of an Actor
:
class Plane : Actor {
};
and you've defined a non-default constructor:
Plane::Plane(double, double) {
// does something
}
As Plane
is a subclass of Actor
, there's an implicit construction of a default Actor
as part of the construction of Plane
, and as you declared that there would be an implementation, the linker is expecting it. As you never defined it in the code, the linker fails at this point.
The somewhat simplistic solution is to add a trivial constructor in actor.h
; namely:
class Actor {
public:
Actor() {} // replace the ; with {}
Actor(double x0, double y0);
void move();
double pos_x();
double pos_y();
static const int ARENA_W = 500;
static const int ARENA_H = 500;
};
Now, as for behaviours here - none of the
move
,pos_x
orpos_y
methods are declaredvirtual
, so they're not being overloaded inPlane
; they're simply being replaced. This may come up later in your course.
来源:https://stackoverflow.com/questions/40870167/c-error-1-error-symbols-not-found-for-architecture-x86-64-in-qt-creat