SORU
21 Kasım 2008, Cuma


Ara C kurucu kurucu

C# bir geliştirici olarak kurucular koşmaya alışkınım:

class Test {
    public Test() {
        DoSomething();
    }

    public Test(int count) : this() {
        DoSomethingWithCount(count);
    }

    public Test(int count, string name) : this(count) {
        DoSomethingWithName(name);
    }
}

Bir şekilde C bunu yapmak için var mı ?

Sınıf adı olarak nitelendirdi ve 'bu' anahtar kelime, ancak her ikisi de başarısız olur. kullanmaya çalıştım

CEVAP
21 Kasım 2008, Cuma


Evet!

Ve sonrası C 11 Bu aynı özellik (delegating constructors olarak adlandırılır) vardır.

Sözdizimi C biraz farklıdır#:

class Foo {
public: 
  Foo(char x, int y) {}
  Foo(int y) : Foo('a', y) {}
};

Ne yazık ki C 03, ama bu taklit iki yolu vardır bunun için bir yol var

1) iki (veya daha fazla) kurucular Varsayılan parametreleri ile birleştirebilirsiniz:

class Foo {
 public:
   Foo(char x, int y=0);  // combines two constructors (char) and (char, int)
   ...
 };

2) init yöntemi ortak kod paylaşmak için Kullanın

class Foo {
 public:
   Foo(char x);
   Foo(char x, int y);
   ...
 private:
   void init(char x, int y);
 };

 Foo::Foo(char x)
 {
   init(x, int(x)   7);
   ...
 }

 Foo::Foo(char x, int y)
 {
   init(x, y);
   ...
 }

 void Foo::init(char x, int y)
 {
   ...
 }

başvuru için this link bkz.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • hotstrikegently

    hotstrikegen

    26 AĞUSTOS 2011
  • Sams Page :D

    Sams Page :D

    15 Mart 2009
  • ShayLoss

    ShayLoss

    5 Kasım 2009