왜 작동하지 않습니까? 가상 함수 GetNOperands()
및 PerformOp()
은 BinaryOp 클래스에 정의되어 있고 DoOp()
은 OpAdd 클래스에 정의되어 있습니다. 연산자 클래스의 가상 Prec()
함수도 OpAdd에 정의되어 있습니다. 파생 클래스의 각 함수에 대한 정의가 하나뿐이므로이 코드에 적용되지 않는다고 생각하는 "다이아몬드 문제"를 조사했습니다.다중 상속 순수 기본 함수
#include <iostream>
#include <vector>
#define PREC_LOW 0
#include <assert.h>
//operator class - abstract
template <class T> class Op {
public:
virtual unsigned int GetNOperands() = 0;
virtual bool PerformOp(std::vector<T>& operands, T& result) = 0;
virtual ~Op() {}
};
//binary operator class - for 2 operators - abstract
template <class T> class BinaryOp : public Op<T> {
public:
unsigned int GetNOperands();
bool PerformOp( std::vector<T>& operands, T& result);
virtual ~BinaryOp() {}
protected:
virtual bool DoOp(T first, T second, T& result) = 0;
};
template <class T> class Operator : public Op<T> {
public:
virtual unsigned int Prec() = 0; //precedence
};
template <class T> class OpAdd : public BinaryOp<T>, public Operator<T> {
public:
unsigned int Prec();
private:
bool DoOp(T first, T second, T& result);
};
template <class T> unsigned int BinaryOp<T>::GetNOperands() {
return 2;
}
template <class T> bool BinaryOp<T>::PerformOp( std::vector<T>& operands, T& result) {
assert(operands.size() == 2);
return DoOp(operands.at(0),operands.at(1),result);
}
template <class T> bool OpAdd<T>::DoOp(T first, T second, T& result) {
result = first + second;
return true;
}
template <class T> unsigned int OpAdd<T>::Prec() {
return PREC_LOW;
}
int main() {
OpAdd<int> a;
return 0;
}
편집 : 컴파일러 오류 상태 :
source.cpp: In function 'int main()':
source.cpp:55:13: error: cannot declare variable 'a' to be of abstract type 'OpAdd<int>'
OpAdd<int> a;
^
source.cpp:30:29: note: because the following virtual functions are pure withi
n 'OpAdd<int>':
template <typename T> class OpAdd : public BinaryOp<T>, public Operator<T> {
^
source.cpp:10:23: note: unsigned int Op<T>::GetNOperands() [with T = int]
virtual unsigned int GetNOperands() = 0;
^
source.cpp:11:15: note: bool Op<T>::PerformOp(std::vector<T>&, T&) [with T = int]
virtual bool PerformOp(std::vector<T>& operands, T& result) = 0;
"작동하지 않음"을 정의하십시오. –
자, 'OpAdd'에서 * 직접 * 기본 클래스'Operator'(및 기본 클래스)의 가상 함수를 재정의하지 않았습니다. –
dyp
나는 컴파일 오류 – joelyboy94