我写了一组类来检查组合模式。基类中的虚函数定义给出了错误
这里是我的代码:
#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中定义它们,我为什么会收到这些错误。如果我不添加这些大胆的声明我的代码工作正常。其次为什么析构函数的错误?
嗯,这里的重点是,如果一个非虚函数永远不会被调用,那么您可以逃避不提供定义。在这里,基类方法永远不会被调用(两个子类都会覆盖它们),但定义仍然是必需的 - 所以它实际上与非虚拟案例完全不同。 –