c#多态和c++中不一样的地方

本文深入解析了一段C++代码,详细解释了类继承与虚函数重写的基本原理,通过实例展示了如何在类中实现重写,并阐述了C++底层在调用基类虚函数时的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先看代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    public class myBase
    {
        public myBase()
        {
            printField();
        }

        public virtual void printField()
        {
            Console.WriteLine("base is called");
        }
    }

    public class client:myBase
    {
        public int i = 0;
        public int j;

        public client()
        {
            j = -1;
        }

        public override void printField()
        {
            Console.WriteLine("i = {0}, j={1}",i,j);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            client t = new client();
            t.printField();


        }
    }
}


看到这个代码不知道大家能不能得出最后的答案是什么?

当我刚开始学习的时候我的答案为: 

base is called
x=0,y=-1;
其实正确的答案为:

x=0,y=0;

x=0,y=-1;


解惑:

刚开始得出这个结果的时候,好使让我费解了。为什么?c++会是这样么。不是的。c++的答案是第一个。因为c++在类中只能声明。

搞了好久,采取请教下大神。原来在实现重写的时候,c#的底层会把基类的虚函数从虚拟指针表中重写掉。所以在调用基类的默认构造函数(实例化继承类时)调用的

printField() 函数实际上是继承类中的printField()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码i小学生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值