1. 创建控制台工程,工程文件如下,
//QtOperator.pro
QT -= gui
CONFIG += c++11 console
CONFIG -= app_bundle
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
qoperatorclass.cpp
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
HEADERS += \
qoperatorclass.h
2. 创建操作演示类
//qoperatorclass.h
#ifndef QOPERATORCLASS_H
#define QOPERATORCLASS_H
class QOperatorClass
{
public:
QOperatorClass();
QOperatorClass operator+(const QOperatorClass &rc) const;
QOperatorClass operator*(int m);
void help();
private:
int m_op1;
int m_op2;
};
#endif // QOPERATORCLASS_H
//qoperatorclass.cpp
#include "qoperatorclass.h"
#include
QOperatorClass::QOperatorClass()
{
m_op1 = 1;
m_op2 = 2;
}
QOperatorClass QOperatorClass::operator+(const QOperatorClass &rc) const
{
QOperatorClass temp;
temp.m_op1=m_op1+rc.m_op1;
temp.m_op2=m_op2+rc.m_op2;
return temp;
}
QOperatorClass QOperatorClass::operator*(int m)
{
QOperatorClass temp;
temp.m_op1=m_op1*m;
temp.m_op2=m_op2*m;
return temp;
}
void QOperatorClass::help()
{
qDebug()<<"op1="< }3. 应用
//main.cpp
#include#include "qoperatorclass.h"#includeint main(int argc, char *argv[]){QCoreApplication a(argc, argv);qDebug()<<"add overload class operator+()";QOperatorClass classA;QOperatorClass classB;QOperatorClass classC;classC.help();classC=classA+classB;classC.help();qDebug()<<"\noverload class operator*()";QOperatorClass classE;QOperatorClass classF;classF.help();classF=classE*10;classF.help();return a.exec();}4. 结果
add overload class operator+()
op1= 1 op2= 2
op1= 2 op2= 4overload class operator*()
op1= 1 op2= 2
op1= 10 op2= 20