形式:virtual 函数类型 函数名 ()(在派生类和基类里都要写)
静态成员函数不能是虚函数
1.通过指针实现多态
对于基类的对象:调用基类的虚函数
对于派生类的对象:调用派生类的虚函数
#include <iostream>
using namespace std;
class A
{ public:
virtual void Print()
{ cout << "print A" << endl;
}
};
class B: public A
{ public:
virtual void Print()
{ cout << "print B" << endl;
}
};
class C: public A
{ public:
virtual void Print()
{ cout << "print C" << endl;
}
};
int main()
{ A a1;
A a2;
B b;
C c;
A *pa1 = &a1;
A *pa2 = &a2;
C *pc = &c;
pa1->Print();
pa1 = &b;
pa1->Print();
pa2 = pc;
pa2->Print();
return 0;
}
2.通过基类的引用实现多态
#include <iostream>
using namespace std;
class A
{ public:
virtual void Print()
{ cout << "print A" << endl;
}
};
class B: public A
{ public:
virtual void Print()
{ cout << "print B" << endl;
}
};
void in(A &r)//基类的引用
{ r.Print();//是谁的对象就调用谁的Print
}
int main()
{ A a;
B b;
in(a);
in(b);
return 0;
}
标签:函数,基类,多态,virtual,C++,派生类,Print
From: https://blog.51cto.com/u_15810302/6176314