我有个程序 书上叫运行时的多态 你门看下
class call1
{
void called()
{
System.out.println("call1 calling now");
}
}
class call2 extends call1
{
void called()
{
System.out.println("call2 calling now");
}
}
class shishi
{
public static void main(String args[])
{
call1 a=new call1();
call2 b=new call2();
a=b;
a.called();
}
}
运行结果是 call2 calling now!!
但是 拿个下面这C++程序
#include "iostream"
using namespace std; class a{
public:
void called()
{
cout<<"a calling now!";
}
};
class b:public a
{
public:
void called()
{
cout<<"b calling now!";
}
};
int main()
{
a m;
b n;
m=n;
m.called();
system("pause");
}
在C++中运行 按照上面的应该是b calling now 才对啊
可是运行结果却是 a calling now!
怎么回事啊?
class call1
{
void called()
{
System.out.println("call1 calling now");
}
}
class call2 extends call1
{
void called()
{
System.out.println("call2 calling now");
}
}
class shishi
{
public static void main(String args[])
{
call1 a=new call1();
call2 b=new call2();
a=b;
a.called();
}
}
运行结果是 call2 calling now!!
但是 拿个下面这C++程序
#include "iostream"
using namespace std; class a{
public:
void called()
{
cout<<"a calling now!";
}
};
class b:public a
{
public:
void called()
{
cout<<"b calling now!";
}
};
int main()
{
a m;
b n;
m=n;
m.called();
system("pause");
}
在C++中运行 按照上面的应该是b calling now 才对啊
可是运行结果却是 a calling now!
怎么回事啊?
然后就是函数定义的时候没有virtual,这样是不会定义虚函数的
而java的方法默认就是虚函数的,默认就会覆盖父类的方法
call1 a=new call1();
call2 b=new call2();
a=b;
我认为与
call1 a=new call2();
是一样的
call1 a=new call1();
call2 b=new call2();
a=b;
我认为与
call1 a=new call2();
是一样的
============================================
功能一样,意义不一样
call1 a=new call2();
a如果不强制转型的话是不能直接用到call2类扩展了的方法和属性
关键没有用到virtual,c++没有这个标志的话,是不会覆盖父类的方法
而java的方法默认就是虚函数的,默认就会覆盖父类的方法