我遇到“界面”操作数问题。我不知道如何使它工作。我收到编译错误,似乎是在Exp上,但我不知道如何解决它。
#include <iostream>
#include <list>
using namespace std;
class Operand{
public:
Operand();
virtual int make(list<int> &l) = 0;
virtual ~Operand();
};
class Sum : public Operand{
private:
char s;
public:
Sum(char &s) : s(s){};
int make(list<int> &l){
int temp;
list<int>::iterator it = l.begin();
for (temp = 0; it != l.end(); ++it)
temp += *it;
return temp;
}
~Sum(){};
};
class Exp{
private:
Operand s; //This little fella seems to be the culprit
list<int> l;
int res;
public:
Exp(Operand &s, list<int> &l) : s(s), l(l){};
void run(){
res = s.make(l);
}
int get_res(){
return res;
}
~Exp(){};
};
int main(int argc, char const *argv[]){
list<int> l;
l.push_back(1);
l.push_back(2);
l.push_back(3);
char p = '+';
Sum s(p);
Exp e(s, l);
e.run();
cout << e.get_res() << endl;
return 0;
}
编译:
g ++ stacko.cpp -std = c ++ 98 -Wall -pedantic -o stacko
这是我得到的错误:
stacko.cpp:31:10: error: cannot declare field ‘Exp::s’ to be of abstract type ‘Operand’
Operand s;
^
stacko.cpp:6:7: note: because the following virtual functions are pure within ‘Operand’:
class Operand{
^
stacko.cpp:9:14: note: virtual int Operand::make(std::list<int>&)
virtual int make(list<int> &l) = 0;
如果我这样做Exp
Operand *s;
public:
Exp(Operand &s, list<int> &l){
s = s;
l = l;
}
void run(){
res = s->make(l);
}
我得到了另一个错误:
/tmp/ccjzYIRI.o: En la función `Sum::Sum(char&)':
stacko.cpp:(.text._ZN3SumC2ERc[_ZN3SumC5ERc]+0x18): referencia a `Operand::Operand()' sin definir
/tmp/ccjzYIRI.o: En la función `Sum::~Sum()':
stacko.cpp:(.text._ZN3SumD2Ev[_ZN3SumD5Ev]+0x1f): referencia a `Operand::~Operand()' sin definir
/tmp/ccjzYIRI.o:(.rodata._ZTI3Sum[_ZTI3Sum]+0x10): referencia a `typeinfo for Operand' sin definir
collect2: error: ld returned 1 exit status
谢谢!
错误发生在析构函数中:
virtual ~Operand(); //wont work
virtual ~Operand(){} //this Will
Exp应该是这样的:
Operand *s;
public:
Exp(Operand &s, list<int> &l) : s(&s), l(l){};
答案 0 :(得分:1)
在c ++中,您无法实例化抽象类(具有一个或多个纯虚函数的类)。而这正是你在做的事情:
Operand s;
如果你真的想要实例化它,你应该用所有Operand
纯虚函数替换虚函数:
代替:
virtual int make(list<int> &l) = 0;
有:
virtual int make(list<int> &l);