1

因为我们知道构造函数不是在子类中继承的,正如我在上一个问题中所问的那样 单击此处查看问题

我已经写了代码

namespace TestConscoleApplication
{
    abstract public class A
    {
       public int c;
       public int d;

    private  A(int a, int b)
       {
           c = a;
           d = b;

       }
        public virtual void Display1()
        {
            Console.WriteLine("{0}{1}", c, d);
        }
    }
    internal class B : A 
    {
      protected  string Msg;

      public B(string Err)

        {
            Msg = Err;

        }

        public  void Display()
        {
            Console.WriteLine(Msg);
        }
    }



    class Program
    {
        static void Main(string[] args)
        {
            B ObjB = new B("Hello");


            Console.ReadLine();
        }
    }
}

当我编译代码时显示错误

TestConscoleApplication.A.A(int, int)由于其保护级别,错误是不可访问的。

那为什么它显示错误。

4

4 回答 4

4

通过将唯一的构造函数A设为私有,您可以防止派生类在外部构造A

于 2012-06-30T10:31:37.340 回答
1

Derived class constructor always call the base constructor (one of). Making it private you prohibit access to it from outside. In other words you make it impossible to make an instance of A outside A.

Since you made a constructor, the compiler won't generate a default public one for this class for you.

If you want to provide access to it from the class descendant but not from outside, you should make it protected.

于 2012-06-30T10:33:04.517 回答
0

You need to have a constructor for A accessible to B, and use it. Also, the default base constructor is base() (i.e. the parameterless constructor), which doesn't exist on A. Here's one way you can resolve this (nonessential bits removed):

abstract public class A
{
    protected A(int a, int b)
    {
    }
}
internal class B : A
{
    public B(int a, int b, string Err)
        : base(a, b)
    {
    }
}
于 2012-06-30T10:35:14.923 回答
-1

constructors shouldn't be private otherwise you will not be able to create an instance of that class and won't be able to inherit it too, but if you want to create a private constructor create a public one with it too. For more info Go here

于 2012-06-30T10:33:48.427 回答