如何让构造函数具有虚函数的效果?c++
发布网友
发布时间:2022-05-17 09:22
我来回答
共2个回答
热心网友
时间:2023-10-17 04:37
在构造函数里调用一个虚函数。
比如:
#include <iostream>
class Student
{
public:
People() {register();} //register是一个虚函数,执行真正的构造过程。
virtual void register() = 0;
void say() {std::cout<<"My name is "<<name<<std::endl;}
protected:
std::string name;
};
class LiLei : public Student
{
public:
void register() {name = "LiLei";}
};
class HanMeiMei : public Student
{
public:
void register() {name = "HanMeiMei";}
}
void main()
{
Student *st1 = new LiMing();
st1->say();
Student * st2 = new HanMeiMei();
st2->say();
delete st1;
delete st2;
}
热心网友
时间:2023-10-17 04:38
#include<iostream>
class Shape
{
public:
virtual Shape* clone(void) const=0;
virtual ~Shape(void){}
};
class Circle :public Shape
{
public:
explicit Circle(double=1.0);
private:
double radius_;
Circle *clone(void) const;
};
Circle::Circle(double theRadius)
{
radius_ = theRadius;
}
inline Circle* Circle::clone(void) const
{
return new Circle(*this);
}
int main(){
using std::cout;
Shape *x = new Circle(12.2);
Shape *y=x->clone();
delete x;
delete y;
}///:~