1

別のクラスの配列を作成する必要があります。例:

namespace std
{
      public class Car
      {
           double number,id;

           public Car()
           {
               // initializing my variables for example:
               number = Random.nextdouble();
           }

      }
      public class Factory
      {
           public Factory(int num)
           {
               Car[] arr = new Car(num);
           }
      }
}

問題は、次のエラーが発生することです。

'Car' には、'1' 引数を取るコンストラクターが含まれていません

Carクラス内の配列が必要なだけですFactory(車の変数はコンストラクターで初期化されます)。

4

4 に答える 4

9

間違ったブラケットを使用しただけです。配列とインデクサーには常に角かっこを使用します。丸括弧は、メソッド、コンストラクターなどを呼び出すためのものです。つまり、次のことを意味します。

car[] arr = new car[num];

Car従来、.NET 型は Pascal ケースであるため、型はandFactoryではなくcarandにする必要があることに注意してくださいfactory

また、配列を作成した後、各要素は null 参照になることに注意してください。したがって、次のように記述しないでください。

// Bad code - will go bang!
Car[] cars = new Car[10];
cars[0].SomeMethod(0);

その代わり:

// This will work:
Car[] cars = new Car[10];
cars[0] = new Car(); // Populate the first element with a reference to a Car object
cars[0].SomeMethod();
于 2013-03-01T18:52:41.073 に答える
1

配列またはインデクサーを宣言するときは、[]notを使用する必要があります。()

car[] arr = new car[num];
于 2013-03-01T18:54:08.597 に答える
0
using System;
namespace ConsoleApplication1
{
    public class Car
    {
        public double number { get; set; }
        public Car()
        {
            Random r = new Random();            
            number = r.NextDouble();// NextDouble isn't static and requires an instance
        }
    }
    public class Factory
    {
        //declare Car[] outside of the constructor
        public Car[] arr;
        public Factory(int num)
        {
            arr = new Car[num]; 
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Factory f = new Factory(3);
            f.arr[0] = new Car();
            f.arr[1] = new Car();
            f.arr[2] = new Car();
            foreach (Car c in f.arr)
            {
                Console.WriteLine(c.number);
            }
            Console.Read();
        }
    }
}
于 2013-03-01T18:55:40.833 に答える
0

配列のみを使用するように要件が制限されていない場合は、型付きリストを使用できます。

List<Car> = new List<Car>(num); 
//num has to be the size of list, but a list size is dinamically increased.

コードのエラーは、配列を次のように初期化する必要があることです。

public class factory
      {
           public factory(int num)
           {
           car[] arr = new car[num];
           }
      }

よろしく、

于 2013-03-01T18:58:56.187 に答える