2013-03-01 44 views
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' does not contain a constructor that takes '1' arguments

我只是需要有Car陣列,Factory類(汽車變量與它的構造函數初始化)。

+1

什麼是你想用'新車(NUM)'做:

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

在你的代碼中的錯誤是,陣列應該如下初始化? 'num'應該做什麼?你的汽車構造函數不帶參數 – 2013-03-01 18:52:29

+0

@AdamPlocher:是的,但看看問題標題和他試圖分配給它的變量 - 這很清楚他正在嘗試創建一個數組。 – 2013-03-01 18:55:56

+0

是的,我意識到,在評論後不久:-) – 2013-03-01 18:56:16

回答

9

您剛剛使用了錯誤的括號。數組和索引器總是使用方括號。圓括弧是調用方法,構造函數等,你的意思是:

car[] arr = new car[num]; 

需要注意的是傳統的.NET類型的Pascal-套管,所以你的類型應該是CarFactory,而不是carfactory

另外請注意,創建陣列之後,每個元素將是一個空引用 - 所以你不應該寫:

// 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(); 
+0

謝謝,問題解決了。 但另一個問題:我可以在構造函數外部聲明沒有num值的arr嗎?換句話說就是讓數組的大小動態變化? – user1229351 2013-03-01 19:16:49

1

您需要使用[]當你聲明一個數組或索引器時不是()

car[] arr = new car[num]; 
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(); 
     } 
    } 
} 
+0

除了忽略'num',當然... – 2013-03-01 18:56:22

+0

@JonSkeet現在好嗎? – kashif 2013-03-01 19:00:53

+0

@JonSkeet - 在作者自己的例子中,他忽略了'iD'和'num',因爲這個參數並沒有被實際使用。 – 2013-03-01 19:01:43

0

如果你的要求不限制只使用數組,你可以使用一個類型的列表。

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

問候,