为什么此代码会引发LNK2019错误?

时间:2011-11-22 15:32:30

标签: c++ inheritance compiler-errors lnk

我只是通过构建这个简单的程序来确定我理解继承,其中Dog继承自哺乳动物。编译时我收到错误。所有它应该做的是进入哺乳动物和狗,树皮的构造,然后进入哺乳动物和狗的析构。我很抱歉在帖子中缩进了一下,它在Visual Studio中组织得很好。

#include <iostream>
#include <string>
using namespace std;
class Mammal
{
public:
    Mammal();
    Mammal(int age);
    Mammal(int age, int mammal);
    ~Mammal();
    int getAge() {return itsAge;};
    int getWeight() {return itsWeight;};
    void setAge(int x) {itsAge = x;};
    void setWeight(int x) {itsWeight = x;};
    void speak() {cout << "MAMMALALALALALLLL!" << endl;};

private:
    int itsAge, itsWeight;
};

class Dog : public Mammal
{
    public:
        Dog();
        Dog(int age);
        Dog(int age, int weight);
        Dog(int age, int weight, string breed);
        ~Dog();
        void setBreed(string breed) {itsBreed = breed;};
        string getBreed() {return itsBreed;};
        void bark() {cout << "Bark!" << endl;};
    private:
        string itsBreed;
};

Mammal::Mammal()
{
    cout << "Mammal constructor." << endl;
    setAge(0);
    setWeight(0);
}

Mammal::Mammal(int age)
{
    cout << "Mammel(int) constructor." << endl;
    setAge(age);
    setWeight(0);
}

Mammal::Mammal(int age, int weight)
{
    cout << "Mammal(int, int) constructor." << endl;
    setAge(age);
    setWeight(weight);
}

Mammal::~Mammal()
{
    cout << "Mammal deconstructor." << endl;
}

Dog::Dog():
Mammal()
{
    cout << "Dog constructor." << endl;
    setBreed("");
}

Dog::Dog(int age):
Mammal(age)
{
    cout << "Dog(int) constructor." << endl;
    setBreed("");
}

Dog::Dog(int age, int weight):
Mammal(age, weight)
{
    cout << "Dog(int, int) constructor." << endl;
    setBreed("");
}

Dog::Dog(int age, int weight, string breed):
Mammal(age, weight)
{
    cout << "Dog(int, int, string) constructor." << endl;
    setBreed(breed);
}


int main()
{
    Dog Goldie(5, 50, "Lab");
    Goldie.bark();
    system("PAUSE");
    return 0;
}

编译器的输出如下:

1>ClCompile:
1>  main.cpp
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Dog::~Dog(void)" (??1Dog@@QAE@XZ) referenced in function _main
1>c:\users\austin\documents\visual studio 2010\Projects\Inheritance\Debug\Inheritance.exe : fatal error LNK1120: 1 unresolved externals
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:00.31
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

2 个答案:

答案 0 :(得分:5)

您为Dog类声明了析构函数,但没有定义它 你也应该定义它。

    Dog::~Dog(){}

gcc上的错误,清楚地告诉:

  

prog.cpp :(。text + 0xf54):对狗::〜狗()的未定义引用   prog.cpp :(。text + 0xfc3):未定义引用Dog :: ~Dog()

修改后的代码

Working sample

答案 1 :(得分:3)

您尚未为Dog

定义析构函数
Dog::~Dog()
{
    cout << "Dog destructor." << endl;
}