class Animal
{
public:
Animal(string name) : _name(name) {}
virtual void bark() {}
protected:
string _name;
};
//以下是动物实体类
class Cat : public Animal
{
public:
Cat(string name) :Animal(name) {}
void bark() { cout << _name << " bark: miao miao!" << endl; }
};
class Dog : public Animal
{
public:
Dog(string name) :Animal(name) {}
void bark() { cout << _name << "bark: wang wang" << endl; }
};
class Pig : public Animal
{
public:
Pig(string name) :Animal(name) {}
void bark() { cout << _name << "bark: heng heng" << endl; }
};
int main()
{
Animal *p1 = new Cat("加菲猫");
Animal *p2 = new Dog("二哈");
int *p11 = (int*)p1;
int *p22 = (int*)p2;
int tmp = p11[0];
p11[0] = p22[0];
p22[0] = tmp;
p1->bark();
p2->bark();
delete p1;
delete p2;
return 0;
}
输出:
加菲猫bark: wang wang
二哈 bark: miao miao!
class Base
{
public:
virtual void show(int i = 10)
{
cout << "call Base::show i:" << i << endl;
}
};
class Derive : public Base
{
public:
void show(int i = 20)
{
cout << "call Derive::show i:" << i << endl;
}
};
int main()
{
Base *p = new Derive();
/*
push 0Ah -> 函数调用,参数压栈是在编译器就确定好的
mov eax, dword ptr[p]
mov ecx, dword ptr[eax]
call ecx
*/
p->show(); //call Derive::show i:10
//i为基类的默认参数
delete p;
return 0;
}
class Base
{
public:
virtual void show()
{
cout << "call Base::show "<< endl;
}
};
class Derive : public Base
{
//private
private:
void show()
{
cout << "call Derive::show" << endl;
}
};
int main()
{
Base *p = new Derive();
/*
成员方法能不能调用,就是说方法的访问权限是不是public的,是在编译阶段就需要
确定好的
编译阶段:Base::show
*/
p->show();//最终能调用到Derive::show,是在运行时期才确定的
delete p;
return 0;
}
class Base
{
public:
Base()
{
/*
push ebp
mov ebp, esp
sub esp, 4Ch
rep stos esp<->ebp 0xCCCCCCCC (windows VS GCC/G++)
vfptr <- &Base::vftable
*/
cout << "call Base()" << endl;
clear();
}
void clear() { memset(this, 0, sizeof(*this)); }
virtual void show()
{
cout << "call Base::show "<< endl;
}
};
class Derive : public Base
{
public:
Derive()
{
cout << "call Derive()" << endl;
}
void show()
{
cout << "call Derive::show" << endl;
}
};
int main()
{
Base *pb1 = new Base();
pb1->show();
delete pb1;
Base *pb2 = new Derive();
pb2->show();
delete pb2;
return 0;
}