这三个概念一直比较混乱,正好看到了篇帖子,感觉不错,梳理了一下,详见下图:
参考文章:http://blog.sina.com.cn/s/blog_8ddc5c2e01013hbd.html
测试代码:
test.h
#ifndef _TEST_H
#define _TEST_H
#include <iostream>
using std::cout;
using std::endl;
class Base
{
public:
virtual void func1(int a)
{
cout << "base func1 int :" << a << endl;
}
void func2(int a)
{
cout << "base func2 int :" << a << endl;
}
};
class Son: public Base
{
public:
/************ overload ***********/
void func3(std::string str)
{
cout << "overload func3 str :" << str << endl;
}
void func3(int a, int b)
{
cout << "overload func3 int a, int b:" << a << b << endl;
}
/************ override ***********/
virtual void func1(int a)
{
cout << "son override func1 int :" << a << endl;
}
/************ redifine ***********/
void func2(char *str)
{
cout << "son redifine func2 str :" << str << endl;
}
void func2(char ch)
{
cout << "son redifine func2 char :" << ch << endl;
}
};
#endif
main.cpp
#include<iostream>
#include "test.h"
using namespace std;
int main()
{
Son *son = new Son();
cout << " ************ overload ***********" << endl;
son->func3("hello world!");
son->func3("10, 20!");
cout << " ************ override ***********" << endl;
Base *base = new Base();
base->func1(2);
son->func1(1);
base = son;
base->func1(3);
son->Base::func1(4);
cout << " ************ redifine ***********" << endl;
son->Base::func2(5);
char str[] = "hello fox!";
son->func2(str);
son->func2('h');
return 0;
}
编译:
g++ main.cpp -I. --std=c++11
输出:
************ overload ***********
overload func3 str :hello world!
overload func3 str :10, 20!
************ override ***********
base func1 int :2
son override func1 int :1
son override func1 int :3
base func1 int :4
************ redifine ***********
base func2 int :5
son redifine func2 str :hello fox!
son redifine func2 char :h
若本文对您有帮助,请帮忙点赞顶上去,便于更多人搜索,在此谢过!