Qt Creator/C++ 构造函数
以四则运算为例,定义一个C++类:Calculation
calculation.h
#ifndef CALCULATION_H
#define CALCULATION_H
class Calculation
{
public:
Calculation();
static int number;
double add(double a,double b);
double sub(double a,double b);
double mul(double a,double b);
double div(double a,double b);
};
#endif // CALCULATION_H
calculation.cpp
#include "calculation.h"
#define ERROR -1
int Calculation::number = 1024;
Calculation::Calculation()
{
}
double Calculation::add(double a,double b)
{
return a+b;
}
double Calculation::sub(double a,double b)
{
return a-b;
}
double Calculation::mul(double a,double b)
{
return a*b;
}
double Calculation::div(double a,double b)
{
if(b)
return a/b;
else
return ERROR;
}
注意静态成员变量的初始化位置是在主程序前。
widet.cpp调用函数和静态成员变量
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include "calculation.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
Calculation cal_1;//创建一个类对象
qDebug()<<cal_1.mul(3,4);
qDebug()<<cal_1.div(3,0);
qDebug()<<Calculation::number;
}
Widget::~Widget()
{
delete ui;
}
注意,调用一个函数前要先创建一个类对象