0

请看下面的代码

主文件

#include <iostream>
#include <string>

using namespace std;

int main()
{
    system("pause");

    return 0;
}

魔法.h

#pragma once

class Magic
{
public:
    Magic();
    ~Magic();
    virtual void display()=0;
};

拼写.h

#pragma once
#include "Magic.h"
#include <iostream>
#include <string>

using namespace std;

class Spell :
    public Magic
{
public:
    Spell(void);
    Spell(string words);
    ~Spell(void);
    void display();

private:
    string words;
};

拼写.cpp

#include "Spell.h"
#include "Magic.h"
#include <iostream>
#include <string>

using namespace std;



Spell::Spell(void)
{
}

Spell::Spell(string words)
{
    this->words = words;
}


Spell::~Spell(void)
{
    cout << "Delete Spell" << endl;
}

void Spell::display()
{
    cout << "Spell Words: " << words << endl;
}

在这里,我收到错误

1>------ Build started: Project: Revision1_1, Configuration: Debug Win32 ------
1>Spell.obj : error LNK2019: unresolved external symbol "public: __thiscall Magic::~Magic(void)" (??1Magic@@QAE@XZ) referenced in function __unwindfunclet$??0Spell@@QAE@XZ$0
1>Spell.obj : error LNK2019: unresolved external symbol "public: __thiscall Magic::Magic(void)" (??0Magic@@QAE@XZ) referenced in function "public: __thiscall Spell::Spell(void)" (??0Spell@@QAE@XZ)
1>C:\Users\yohan\Documents\Visual Studio 2010\Projects\Revision1_1\Debug\Revision1_1.exe : fatal error LNK1120: 2 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

我不明白在这里做什么。为什么会这样?请帮忙!反正我是 C++ 新手..

4

4 回答 4

3

Magic没有实现它的构造函数和析构函数(也应该是virtual)。

如果没有必要,甚至不要声明构造函数,例如

class Magic {
public:
  virtual ~Magic() {}
  virtual void display() = 0;
};

无关:我不知道你会施展魔法。

于 2012-12-22T15:46:12.257 回答
2

你没有实现

Magic();
~Magic();

您需要在实现文件中内联实现它们,或者将它们标记为= default.

于 2012-12-22T15:45:55.037 回答
2

You have declared a destructor in your Magic class but did not define it. That's why the linker complains (and the compiler doesn't).

于 2012-12-22T15:47:23.283 回答
1

您没有 Magic 的实现。如果您的意图是让 Magic 成为一个抽象基类,那么只需将其声明更改为:

#pragma once

class Magic
{
public:
    virtual void display()=0;
};

Remember, any method that is not followed by = 0 in the interface must be implemented in the class.

于 2012-12-22T15:46:52.060 回答