我想超载<<< atraft class class 作为虚拟操作员,我知道如何超载操作员的运算符下面的简单类和代码是一个示例。
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;
}
但是现在,假设我们有摘要baseclass,如下
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;
}
现在我想超载&lt;&lt;摘要baseclass的操作员应该实施哪个孩子。
这是我的尝试
#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
编译器抱怨:虚拟外部班级声明,您有任何想法吗?
我尝试并成功编译的内容,您如何看待此方法,并且有更好的成就。
这是抽象类
.h
#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);
virtual QDataStream &serialize(QDataStream &stream)=0;
private :
int m_BaseFirstField;
int m_BaseSecondField;
};
QDataStream &operator<<(QDataStream &out, AbstractBaseClass &obj);
#endif // ABSTRACTBASECLASS_H
.cpp
#include "abstractbaseclass.h"
AbstractBaseClass::AbstractBaseClass()
{
m_BaseFirstField = 0;
m_BaseSecondField = 0;
}
int AbstractBaseClass::BaseFirstField() const
{
return m_BaseFirstField;
}
void AbstractBaseClass::setBaseFirstField(int BaseFirstField)
{
m_BaseFirstField = BaseFirstField;
}
int AbstractBaseClass::BaseSecondField() const
{
return m_BaseSecondField;
}
void AbstractBaseClass::setBaseSecondField(int BaseSecondField)
{
m_BaseSecondField = BaseSecondField;
}
QDataStream &operator<<(QDataStream &out, AbstractBaseClass &obj)
{
return obj.serialize(out);
}
和儿童课
class ChildClass : public AbstractBaseClass
{
public:
ChildClass(){}
int ChildFirstField() const
{
return m_ChildFirstField;
}
void setChildFirstField(int ChildFirstField)
{
m_ChildFirstField = ChildFirstField;
}
private:
int m_ChildFirstField;
// AbstractBaseClass interface
public:
QDataStream &serialize(QDataStream &stream) override
{
stream << BaseFirstField();
stream << BaseSecondField();
stream << ChildFirstField();
return stream;
}
};