我想将抽象类的<<运算符重载为虚拟运算符,我知道如何为简单类重载运算符,下面的代码是一个示例。
class NormalClass
{
public:
int firstField() const;
void setFirstField(int firstField);
int secondField() const;
void setSecondField(int secondField);
private:
int m_firstField;
int m_secondField;
};
QDataStream &operator<<(QDataStream &out, const NormalClass &obj)
{
out << obj.firstField();
out << obj.secondField();
return out;
}
但是现在假设我们有如下的 AbstractBaseClass、ChildClass
class AbstractBaseClass
{
public:
AbstractBaseClass() {}
int BaseFirstField() const;
void setBaseFirstField(int BaseFirstField);
int BaseSecondField() const;
void setBaseSecondField(int BaseSecondField);
private :
int m_BaseFirstField;
int m_BaseSecondField;
};
class ChildClass : public AbstractBaseClass
{
public:
ChildClass() {}
int ChildFirstField() const;
void setChildFirstField(int ChildFirstField);
private:
int m_ChildFirstField;
}
现在我想为应该实现它的 AbstractBaseClass 重载 << 运算符。
这是我的尝试
#ifndef ABSTRACTBASECLASS_H
#define ABSTRACTBASECLASS_H
#include <QDataStream>
class AbstractBaseClass
{
public:
AbstractBaseClass();
int BaseFirstField() const;
void setBaseFirstField(int BaseFirstField);
int BaseSecondField() const;
void setBaseSecondField(int BaseSecondField);
private :
int m_BaseFirstField;
int m_BaseSecondField;
};
virtual QDataStream &operator<<(QDataStream &out, const AbstractBaseClass &obj)=0;
#endif // ABSTRACTBASECLASS_H
编译器抱怨:虚拟外部类声明,你知道吗?