C++\C# 语言的差别 一一 构造函数中对虚函数的调用
2014-01-11 18:27 jx02 阅读(553) 评论(0) 收藏 举报昨天有个WPF绑定问题,需要在构造函数中调用虚函数。按照以往C++的使用经验,构造函数中调用虚函数是不会起作用的。主要原因是C++对象尚未构建成功,虚函数表vtable没有创建好,无法产生多态效果。
而C#早在.NET3.5就引入虚属性 virtual property,我不由得推断在C#构造函数中调用虚函数一定是可以的。在网上找了半天,此类博文demo较少。自己在VS2010中做了个demo实证一把,确定在C#构造函数中调用虚函数可实现多态的。
不多说了,直接上代码
// DemoCtor2.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "stdio.h" #include <iostream> using namespace std; class Base { public: Base() { Fuction(); } virtual void Fuction() { cout << "Base::Fuction" << endl; } }; class A : public Base { public: A() { Fuction(); } virtual void Fuction() { cout << "A::Fuction" << endl; } }; int _tmain(int argc, _TCHAR* argv[]) { int i; cout << "--------new Base--------" << endl; Base* b = new Base(); cout << endl; cout << "--------new A--------" << endl; Base* b2 = new A(); cin>>i; return 0; }
输出结果:
--------new Base-------- Base::Fuction --------new A-------- Base::Fuction A::Fuction
接下来看看C#的表现:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DemoVirtualCtor { class Program { static void Main(string[] args) { A a = new B();//x=1,y=0 a.PrintFields();//x=1,y=-1 B b = new B();//x=1,y=0 b.PrintFields();//x=1,y=-1 A c = new A(); c.PrintFields();//什么都不输出 Console.ReadKey(); } } class A { public A() { PrintFields(); } public virtual void PrintFields() { Console.WriteLine("A"); } } class B : A { int x = 1; int y; public B() { y = -1; } public override void PrintFields() { Console.WriteLine("B : x={0},y={1}", x, y); } } }
输出结果:
B : x=1,y=0 B : x=1,y=-1 B : x=1,y=0 B : x=1,y=-1 A A
为何在C#构造函数中调用虚函数可实现多态 ?待深入探索......
后记:最近几年的项目一直都是混合使用VC、C#,而在此之前若干年一直用的是VC。长期使用两种语言后,深感不同语言无优劣,要把它们用在合适的地方,发挥它们的长处。界面使用VC太笨重,效率太低。若在底层系统中用C#,
单执行效率上可能要相对VC降一个数量级。后续会继续总结一些使用经验。