问题
I am trying to use class inheritance. I have taken a code from a book and tweaked it a bit to create Class Mammal and a Class Dog which inherits Mammal member data. The code is:
#include<iostream>
enum BREED{Labrador,Alcetian,Bull,Dalmetian,Pomerarian};
class Mammal{
public:
Mammal();
~Mammal(){}
double getAge(){return age;}
void setAge(int newAge){age=newAge;}
double getWeight(){return weight;}
void setWeight(double newWeight){weight=newWeight;}
void speak(){std::cout<<"Mammal sound!\n";}
protected:
int age;
double weight;
};
class Dog : public Mammal{
public:
Dog();
~Dog(){}
void setBreed(BREED newType){type=newType;}
BREED getBreed(){return type;}
private:
BREED type;
};
int main(){
Dog Figo;
Figo.setAge(2);
Figo.setBreed(Alcetian);
Figo.setWeight(2.5);
std::cout<<"Figo is a "<<Figo.getBreed()<<" dog\n";
std::cout<<"Figo is "<<Figo.getAge()<<" years old\n";
std::cout<<"Figo's weight is "<<Figo.getWeight()<<" kg\n";
Figo.speak();
return 0;
}
When I run this code,, it gives me the following error:
C:\cygwin\tmp\cc7m2RsP.o:prog3.cpp:(.text+0x16): undefined reference to `Dog::Dog()' collect2.exe: error: ld returned 1 exit status
Any help would be appreciated. Thanks.
回答1:
You didn't define constructors, you only declared them:
class Mammal{
public:
Mammal(); // <-- declaration
...
class Dog : public Mammal{
public:
Dog(); // <-- declaration
When you declare a constructor (or any function) then the C++ compiler will look for the constructor's definition elsewhere. And when it can't find it it complains. For basic definitions try this:
class Mammal{
public:
Mammal() {}; // <-- definition
...
class Dog : public Mammal{
public:
Dog() {}; // <-- definition
You can also remove them entirely since they don't seem to do anything (C++ will insert default constructor for you).
回答2:
You have declared constructor for the class Dog::Dog();
, its not defined. Means constructor is missing body. Define a constructor as follows
public:
Dog::Dog(){
//statements
}
回答3:
This because you have just declared the non-parameterized constructors Dog();
and Mammal();
in respective classes, but not defined it.
To remove the error do following:
- In
class Mammal
, change lineMammal();
toMammal(){}
AND - In
class Dog
, change lineDog();
toDog() {}
.
来源:https://stackoverflow.com/questions/47752165/undefined-reference-compilation-error