class Base
{
//定义了一个名为i的实例变量
int i = 2;
public Base()
{
//直接输出this.i
System.out.printf("Base() %d\n",this.i);
this.display();
//输出this实际的类型,将看到输出Derived
System.out.println("public Base() "+this.getClass());
//因为this的编译类型是Base,所以依然不能调用sub()方法,
//this.sub();
}
public void display()
{
System.out.printf("Base::display() %d\n",i);
}
}
//继承Base的Derived子类
class Derived extends Base
{
//定义了一个名为i的实例变量
//private int i = 22;
//构造器,将实例变量i初始化为222
public Derived()
{
i = 222;
System.out.println("public Derived() "+this.getClass());
System.out.printf("Derived() ,i=%d\n",i);
this.display();
}
public void display()
{
System.out.printf("Derived::display() %d\n",i);
}
public void sub(){}
}
public class Test3
{
public static void main(String[] args)
{
//创建Derived的构造器创建实例
new Derived();
}
}
/*
Base() 2
Derived::display() 2
public Base() class Derived
public Derived() class Derived
Derived() ,i=222
Derived::display() 222
请按任意键继续. . .
*/
#include <stdio.h>
#include <iostream>
using namespace std;
class Base
{
public:
Base *x;
Base()
{
cout<<"Create:"<<typeid(this).name()<<endl;
x=this;
}
~Base()
{
cout<<"Delete:"<<typeid(this).name()<<endl;
}
virtual void test()
{
cout<<"Base test "<<typeid(this).name()<<endl;
}
};
class inat:public Base
{
public:
inat()
{
cout<<"Create:"<<typeid(this).name()<<endl;
}
~inat()
{
cout<<"Delete:"<<typeid(this).name()<<endl;
}
virtual void test()
{
cout<<"inat test "<<typeid(this).name()<<endl;
}
void sss()
{
x->test();
}
};
void main()
{
inat s;
s.test();
s.sss();//Base test class Base *//因为test没有virtual,加了virtual变为inat test class inat *
}
/*
Create:class Base *
Create:class inat *
inat test class inat *
inat test class inat *
Delete:class inat *
Delete:class Base *
Press any key to continue
*/
class Base { //定义了一个名为i的实例变量 int i = 2; public Base() { //直接输出this.i System.out.printf("Base() %d\n",this.i); this.display(); //输出this实际的类型,将看到输出Derived System.out.println("public Bas