B类 继承自A类。 A类有一虚方法,无任何实现。 B类重写.........输出结果

 class Program
    {
        static void Main(string[] args)
        {
            B b = new B();   // ①  首先实例化B时,执行B的构造函数,跳转到②
            b.PrintFields(); //④   //此处输出x= 1 y = -1
            Console.ReadKey();
        }
    }
    class A
    {
        public A()  //③
        {
            PrintFields();  //执行此代码(实际上是B的方法),是B继承了A的构造函数吗?????疑问。。。  此处输出x=1,y=0.还未调用B的构造函数。   再跳转到②
        }
        public virtual void PrintFields() { }
    }
    class B : A
    {
        int x = 1;
        int y;
        public B() //②    由于B继承A,先执行A的构造函数,跳转到③
        {
            y = -1;  //由③跳转回来后执行,初始化完毕  跳转到④
        }
        public override void PrintFields()
        {
            Console.WriteLine("x={0},y={1}", x, y);
        }

    }

输出结果:

x=1,y=0;

x= 1 y = -1

一、

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的 C++ 代码示例,用继承的方法创建了一个 Shape ,它有两个派生:Circle 和 Rectangle,实现了多态操作。 ```c++ #include <iostream> using namespace std; // Shape class Shape { protected: int width, height; public: Shape( int a = 0, int b = 0) { width = a; height = b; } virtual int area() { cout << "Parent class area :" <<endl; return 0; } }; // Circle class Circle: public Shape { public: Circle( int a = 0, int b = 0) : Shape(a, b) { } int area () { cout << "Circle class area :" <<endl; return (width * height * 3); } }; // Rectangle class Rectangle: public Shape{ public: Rectangle( int a = 0, int b = 0) : Shape(a, b) { } int area () { cout << "Rectangle class area :" <<endl; return (width * height); } }; int main() { Shape *shape; Circle circle(10,7); Rectangle rectangle(5,6); // 存储 Circle 的地址 shape = &circle; // 调用 Circle 的 area shape->area(); // 存储 Rectangle 的地址 shape = &rectangle; // 调用 Rectangle 的 area shape->area(); return 0; } ``` 输出结果为: ``` Circle class area : Rectangle class area : ``` 在这个例子中,Shape 是一个基,Circle 和 Rectangle 是它的派生。通过在 Shape 中定义一个虚函数 area(),在派生中分别重写该函数,实现了多态操作。在主函数中,分别创建了 Circle 和 Rectangle 的对象,然后用一个指向 Shape 的指针分别指向这两个对象,调用 area() 函数,输出了不同的结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值