gpt4 book ai didi

c++ - 基类中的虚函数定义出错

转载 作者:行者123 更新时间:2023-11-30 01:55:34 25 4
gpt4 key购买 nike

我写了一组类来检查组合模式。

这是我的代码:

#include <iostream>
#include <string>
#include <list>
#include "InvalidCompositeException.h"

using namespace std;
class Composite;
class Component {
public:
Component() {}
virtual ~Component() {}
virtual string getName() = 0;
virtual int getNetPrice() = 0;

virtual Composite* getComposite() {
try {
throw myEx;
} catch (InvalidCompositeException& e) {
cout<<"Exception: "<<e.what();
}
return 0;
}
**virtual void add(Component* c);
virtual void remove(Component* c);**
private:

};

class Composite : public Component {
public:
Composite():mChildList(new list<Component*>()) {}
virtual ~Composite() {
mChildList->clear();
delete mChildList;
}
virtual string getName() {return "Composite";}
virtual int getNetPrice() {
list<Component*>::iterator i;
int sum = 0;
for(i=mChildList->begin(); i!= mChildList->end(); ++i) {
sum = sum + (*i)->getNetPrice();
}
return sum;
}
virtual void add(Component* c) {
mChildList->push_back(c);
}
virtual void remove(Component* c) {
mChildList->remove(c);
}

private:
list<Component*>* mChildList;
};

class Container: public Composite {
public:
Container() {}
virtual ~Container() {}
string getName() {
cout<<"container"<<endl;
return "container";
}
};

class Line: public Component {
public:
Line(): mNetPrice(50) {}
~Line() {};
int getNetPrice() { return mNetPrice; }
string getName() {
cout<<"line"<<endl;
return "line";
}

private:
int mNetPrice;
};

class Text: public Component {
public:
Text(): mNetPrice(100) {}
~Text() {};
int getNetPrice() { return mNetPrice; }
string getName() {
cout<<"Text"<<endl;
return "Text";
}
private:
int mNetPrice;
};

int main(void) {
Container* c = new Container();
Line* l = new Line();
Text* t = new Text();
c->add(l);
c->add(l);
c->add(t);
cout<<"total price for c is "<<c->getNetPrice();
l->getComposite();
delete t;
delete l;
delete c;
return EXIT_SUCCESS;
}

我的代码运行正常,除非我在我的父类中添加那些粗线时收到错误

undefined reference to `vtable for Component'   // on this line virtual ~Component() {}
undefined reference to `Component::add(Component*)'
undefined reference to `Component::remove(Component*)'

我没有将虚函数定义为纯虚函数。那为什么我会收到这些错误,即使我没有在 Line 和 Text Classes 中定义它们。如果我不添加那些大胆的声明,我的代码就可以正常工作。其次,为什么析构函数出错?

最佳答案

非纯虚函数需要有一个定义,即使它们从未被调用(以便链接器有一些东西可以放入 vtable 中)。只需添加 =0 即可使您的类抽象,或提供空定义。

析构函数的错误有点复杂,但基本上编译器需要决定在哪个目标文件中为你的多态类放置 vtable——它通常在第一个非-定义了纯非内联虚函数(在没有此类函数的地方有更复杂的规则)。在这种情况下,您声明了两个外联虚函数,但从未定义它们,因此编译器永远不会将 vtable 写入目标文件。

关于c++ - 基类中的虚函数定义出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20612177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com