【发布时间】:2015-01-18 08:46:30
【问题描述】:
我正在定义一个“函数”类和另外两个从“函数”继承的“多项式”和“仿射”类。
class function {
public:
function(){};
virtual function* clone()const=0;
virtual float operator()(float x)const=0; //gives the image of a number by the function
virtual function* derivative()const=0;
virtual float inverse(float y)const=0;
virtual ~function(){}
};
class polynomial : public function {
protected:
int degree;
private:
float *coefficient;
public:
polynomial(int d);
virtual~polynomial();
virtual function* clone()const;
int get_degree()const;
float operator[](int i)const; //reads coefficient number i
float& operator[](int i); //updates coefficient number i
virtual float operator()(float x)const;
virtual function* derivative()const;
virtual float inverse(float y)const;
};
class affine : public polynomial {
int a;
int b;
//ax+b
public:
affine(int d,float a_, float b_);
function* clone()const;
float operator()(float x)const;
function* derivative()const;
float inverse(float y)const;
~affine(){}
};
我实现了与“多项式”相关的所有方法,并希望对其进行测试。对于派生方法,我在实例度数等于0的情况下使用仿射构造函数。所以我必须在运行测试之前定义这个构造函数。
polynomial::polynomial(int d)
{
assert(d>=0);
degree=d;
coefficient=new float [d+1];
}
polynomial::~polynomial()
{
delete[] coefficient;
}
function* polynomial::derivative()const
{
if(degree==0)
{
return new affine(0,0,0);
}
polynomial* deriv=new polynomial(degree-1);
for(int i=0;i<degree;i++)
deriv[i]=(i+1)*coefficient[i+1];
return deriv;
}
affine::affine(int d,float a_, float b_):polynomial(d)
{
assert(d==0 || d==1);
degree=d;
a=a_;
b=b_;
}
我的第一个测试是:
#include "function.h"
int main(int argc, const char * argv[])
{
//p=x^3
polynomial p(3);
for(int i=0;i<=2;i++) p[i]=0;
p[3]=1;
cout<<"21^(1/3)="<<p.inverse(21);
return 0;
}
当我运行它时,我得到一个链接错误:
Undefined symbols for architecture x86_64:
"vtable for affine", referenced from:
affine::affine(int, float, float) in polynomial.o
NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
我不知道为什么。
【问题讨论】:
-
你确定你有一个
virtual ~polynomial()的定义吗? (而不仅仅是一个声明)。 -
问题的执行示例将有助于回答问题。
-
你在子类中实现了逆向吗?
-
听起来您没有定义在
affine中声明的所有虚函数(如错误消息中的注释所述)。具体来说,您是否定义了第一个affine::clone? -
我已经像这样实现了~polynomial():polynomial::~polynomial() { delete[] coefficient;在“逆”方面,我只是为“多项式”实现了它。 “仿射”中没有虚拟方法,但我没有定义“仿射”中的所有方法,因为我想先测试“多项式”及其方法,然后再进行其他操作