#include <iostream>
using namespace std;
class Base
{
public:
virtual void f()
{
this->print(); //为什么此处其知道指向的是派生类对象而非派生类对象的基类部分
}
virtual void print(int i=6)
{
cout<<"Base:"<< i*i <<endl;
}
};
class Derived : virtual public Base
{
public:
virtual void f()
{
this->print(); //
}
virtual void print(int i=10)
{
cout<<"Derived" << i*i<<endl;
}
};
void bar(Base* p)
{
p->print();
p->f();
}
int main()
{
Base * p = new Base;
bar(p);
Derived * q = new Derived();
bar(q);
Base * r = (Base *)new Derived();
bar(r);
return 0;
}
结果是:
Base:36
Base:36
Derived36
Derived100
Derived36
Derived100
求问为啥派生类执行第一次 print()时i的值不是10而是6第二次又变成10,求大神快来救我
using namespace std;
class Base
{
public:
virtual void f()
{
this->print(); //为什么此处其知道指向的是派生类对象而非派生类对象的基类部分
}
virtual void print(int i=6)
{
cout<<"Base:"<< i*i <<endl;
}
};
class Derived : virtual public Base
{
public:
virtual void f()
{
this->print(); //
}
virtual void print(int i=10)
{
cout<<"Derived" << i*i<<endl;
}
};
void bar(Base* p)
{
p->print();
p->f();
}
int main()
{
Base * p = new Base;
bar(p);
Derived * q = new Derived();
bar(q);
Base * r = (Base *)new Derived();
bar(r);
return 0;
}
结果是:
Base:36
Base:36
Derived36
Derived100
Derived36
Derived100
求问为啥派生类执行第一次 print()时i的值不是10而是6第二次又变成10,求大神快来救我