第一种情况,当基类和子类中声明的是同名非虚函数时.调用关系如下
#include <iostream>
using namespace std;
#include <bits/stdc++.h>
class AAA
{
public:
void test1()
{
printf("This is AAA: test1()\n");
test2();
}
void test2(){
printf("This is AAA: test2()\n");
}
};
class BBB : public AAA
{
public:
void test2(){
printf("This is BBB: test2()\n");
}
};
int main() {
BBB *p = new BBB;
p->test1();
return 0;
}
结果输出:
This is AAA: test1()
This is AAA: test2()
可以看到当子类指针所调用函数只存在于基类中时,调用的是基类的函数,当此时在基类函数中调用与子类函数中的同名函数时,调用的依旧是基类中的函数,这个我的理解就是积累函数中操作的this指针只能调用基类函数.
第二种情况,当基类指针指向派生类对象时,调用非虚函数的情况.
#include <iostream>
using namespace std;
#include <bits/stdc++.h>
class AAA
{
public:
void test1()
{
printf("This is AAA: test1()\n");
test2();
}
void test2(){
printf("This is AAA: test2()\n");
}
};
class BBB : public AAA
{
public:
void test1()
{
printf("This is AAA: test1()\n");
test2();
}
void test2(){
printf("This is BBB: test2()\n");
}
};
int main() {
AAA *p = new BBB;
p->test1();
return 0;
}
输出结果:
This is AAA: test1()
This is AAA: test2()
如果基础类和衍生类定义了相同名称的成员函数(非虚函数),那么通过对象指针调用成员函数时,到底调用哪个函数要根据指针的类型(基类指针or派生类指针)来确定,而不是根据指针实际指向的对象类型确定
第三种情况,当基类中函数被声明为虚函数时,子类中重写该函数,最终子类指针调用结果.
#include <iostream>
using namespace std;
#include <bits/stdc++.h>
class AAA
{
public:
void test1()
{
printf("This is AAA: test1()\n");
test2();
}
virtual void test2(){
printf("This is AAA: test2()\n");
}
};
class BBB : public AAA
{
public:
void test2(){
printf("This is BBB: test2()\n");
}
};
int main() {
BBB *p = new BBB;
p->test1();
return 0;
}
输出结果为:
This is AAA: test1()
This is BBB: test2()
可以看出当调用的同名函数在基类中声明为虚函数时,调用的函数取决于指针实际指向的对象类型(基类对象or派生类对象)来确定,而不是根据指针的类型确定。
第四种情况,当基类与子类定义同名函数(虚函数),函数调用情况.
#include <iostream>
using namespace std;
#include <bits/stdc++.h>
class AAA
{
public:
virtual void test1()
{
printf("This is AAA: test1()\n");
test2();
}
virtual void test2(){
printf("This is AAA: test2()\n");
}
};
class BBB : public AAA
{
public:
void test1()
{
printf("This is BBB: test1()\n");
test2();
}
void test2(){
printf("This is BBB: test2()\n");
}
};
int main() {
AAA *p = new BBB;
p->test1();
return 0;
}
输出结果:
This is BBB: test1()
This is BBB: test2()
如果基础类和衍生类定义了相同名称的成员函数(虚函数virtual),那么通过对象指针调用成员函数时,到底调用哪个函数要根据指针实际指向的对象类型(基类对象or派生类对象)来确定,而不是根据指针的类型确定
第五种情况,当子类指针指向基类对象时,调用非虚函数的情况
#include <iostream>
using namespace std;
#include <bits/stdc++.h>
class AAA
{
public:
void test1()
{
printf("This is AAA: test1()\n");
test2();
}
void test2(){
printf("This is AAA: test2()\n");
}
};
class BBB : public AAA
{
public:
void test1()
{
printf("This is AAA: test1()\n");
test2();
}
void test2(){
printf("This is BBB: test2()\n");
}
};
int main() {
BBB *p = new AAA;
p->test1();
return 0;
}
输出结果:
Compilation Failed
所以不要这样写,与是不是虚函数无关.