基类不包含无参构造器? [英] Base Class Doesn't Contain Parameterless Constructor?

查看:148
本文介绍了基类不包含无参构造器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过删除一些空的构造函数使我的构造函数更严格。我对继承很新,并对我遇到的错误困惑:基类不包含无参构造器。如何使A2从A继承,而在A中没有一个空构造函数。另外,为了我个人的理解,为什么A2需要一个空的构造函数为A?

I'm making my constructors a bit more strict by removing some of my empty constructors. I'm pretty new to inheritance, and was perplexed with the error that I got: Base Class Doesn't Contain Parameterless Constructor. How can I make A2 inherit from A without there being an empty constructor in A. Also, for my own personal understanding, why is A2 requiring an empty constructor for A?

Class A{
    //No empty constructor for A
    //Blah blah blah...
}

Class A2 : A{
    //The error appears here
}


推荐答案

在类A2中,您需要确保所有的构造函数都使用参数调用基类构造函数。

In class A2, you need to make sure that all your constructors call the base class constructor with parameters.

否则,编译器将假设你想使用无参数的基类构造函数来构造你的A2对象所基于的A对象。

Otherwise, the compiler will assume you want to use the parameterless base class constructor to construct the A object on which your A2 object is based.

示例:

class A
{
    public A(int x, int y)
    {
        // do something
    }
}

class A2 : A
{
    public A2() : base(1, 5)
    {
        // do something
    }

    public A2(int x, int y) : base(x, y)
    {
        // do something
    }

    // This would not compile:
    public A2(int x, int y)
    {
        // the compiler will look for a constructor A(), which doesn't exist
    }
}

这篇关于基类不包含无参构造器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆