C++函数重载、重写与重定义
一、函数重载
1.定义
定义:相同函数名称,不同参数序列(包括参数的个数不同或参数的类型不同)。
2.基本条件
基本条件:
函数名必须相同;
函数参数必须不相同,可以是参数类型或者参数个数不同;
函数返回值可以相同,也可以不相同。(备注:但是如果函数的名称和参数完全相同,仅仅是返回值类型不同,是无法进行函数重载的。)
3.代码(chongzai类)
(1)chongzai.h
#ifndef CHONGZAI_H
#define CHONGZAI_H
class chongzai
{
public:
chongzai();
int compare(int a,int b);
int compare(int c);
double compare(double a, double b);
};
#endif // CHONGZAI_H
(2)chongzai.cpp
#include "chongzai.h"
chongzai::chongzai()
{
}
int chongzai::compare(int a, int b)
{
return a>b?a:b;
}
int chongzai::compare(int c)
{
int b=2*c-1;
return b>c?b:c;
}
double chongzai::compare(double c, double d)
{
return c>d?c:d;
}
(3)main.cpp
#include "widget.h"
#include <QApplication>
#include <QDebug>
#include "chongzai.h"
int main(int argc, char *argv[])
{
// QApplication a(argc, argv);
// Widget w;
// w.show();
chongzai *aa4=new chongzai;
int a1=22,b=41;
double c=2.1,d=1.1;
int res=aa4->compare(a1,b);
qDebug()<<"res="<<res<<endl;
double res1=aa4->compare(c,d);
qDebug()<<"res1="<<res1<<endl;
int res2=aa4->compare(a1);
qDebug()<<"res2="<<res2<<endl;
//return a.exec();
}
4.运行结果
二、函数重写
1.定义
定义:子类重新定义父类中有相同名称和参数的虚函数,主要在继承关系中出现
2.基本条件
基本条件:
重写的函数和被重写的函数必须都为virtual函数,并分别位于基类和派生类中;
重写的函数和被重写的函数,函数名和函数参数必须完全一致;
重写的函数和被重写的函数,返回值相同,或者返回指针或引用,并且派生类虚函数返回的指针或引用的类型是基类中被替换的虚函数返回的指针或引用的类型或者其子类型(派生类型)。
3.代码( chongxie类)
(1)chongxie.h
#ifndef CHONGXIE_H
#define CHONGXIE_H
class chongxieA
{
public:
chongxieA();
virtual void show();
};
class chongxieB:public chongxieA
{
public:
chongxieB();
void show();
};
class chongxieC:public chongxieA
{
public:
chongxieC();
// void show();
};
#endif // CHONGXIE_H
(2)chongxie.cpp
#include "chongxie.h"
#include <QDebug>
chongxieA::chongxieA()
{
}
chongxieB::chongxieB()
{
}
chongxieC::chongxieC()
{
}
void chongxieA::show()
{
qDebug()<<"父类A"<<endl;
}
void chongxieB::show()
{
qDebug()<<"子类B"<<endl;
}
(3)main.cpp
chongxieA* b=new chongxieB;//重写:子类函数
b->show();
chongxieA* c=new chongxieC;//未重写:父类函数
c->show();
4.运行结果
三、函数重载
1.定义
函数重定义:父类和子类中有相同名称的非虚函数,返回值类型、参数列表可以不同。子类对象调用该同名方法时,子类方法将覆盖父类方法
2.基本条件
返回值类型、参数列表可以不同。
子类对象调用该同名方法时,子类方法将覆盖父类方法
3.代码(chongdingyi类)
(1)chongdingyi.h
#ifndef CHONGDINGYI_H
#define CHONGDINGYI_H
class chongdingyiA
{
public:
chongdingyiA();
void show();
};
class chongdingyiB:public chongdingyiA
{
public:
chongdingyiB();
void show();
};
#endif // CHONGDINGYI_H
(2)chongdingyi.cpp
#include "chongdingyi.h"
#include <QDebug>
chongdingyiA::chongdingyiA()
{
}
chongdingyiB::chongdingyiB()
{
}
void chongdingyiA::show()
{
qDebug()<<"函数重定义:父类"<<endl;
}
void chongdingyiB::show()
{
qDebug()<<"函数重定义:子类"<<endl;
}
(3)main.cpp
chongdingyiA* a=new chongdingyiB;
a->show();
chongdingyiB* b=new chongdingyiB;
b->show();
4.运行结果