Konstruktory C++


Konstruktorzy

Konstruktor w C++ to specjalna metoda , która jest automatycznie wywoływana podczas tworzenia obiektu klasy.

Aby utworzyć konstruktor, użyj tej samej nazwy co klasa, a następnie nawiasów ():

Przykład

class MyClass {     // The class
  public:           // Access specifier
    MyClass() {     // Constructor
      cout << "Hello World!";
    }
};

int main() {
  MyClass myObj;    // Create an object of MyClass (this will call the constructor)
  return 0;
}

Uwaga: Konstruktor ma taką samą nazwę jak klasa, zawsze jest publici nie ma żadnej wartości zwracanej.


Parametry konstruktora

Konstruktory mogą również przyjmować parametry (podobnie jak zwykłe funkcje), które mogą być przydatne do ustawiania początkowych wartości atrybutów.

Następująca klasa ma atrybuty brandi modeloraz yearkonstruktor z różnymi parametrami. Wewnątrz konstruktora ustawiamy atrybuty równe parametrom konstruktora ( brand=x, itd.). Kiedy wywołujemy konstruktor (tworząc obiekt klasy), przekazujemy parametry do konstruktora, który ustawi wartości odpowiednich atrybutów na takie same:

Przykład

class Car {        // The class
  public:          // Access specifier
    string brand;  // Attribute
    string model;  // Attribute
    int year;      // Attribute
    Car(string x, string y, int z) { // Constructor with parameters
      brand = x;
      model = y;
      year = z;
    }
};

int main() {
  // Create Car objects and call the constructor with different values
  Car carObj1("BMW", "X5", 1999);
  Car carObj2("Ford", "Mustang", 1969);

  // Print values
  cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
  cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
  return 0;
}

Podobnie jak funkcje, konstruktory można również definiować poza klasą. Najpierw zadeklaruj konstruktor wewnątrz klasy, a następnie zdefiniuj go poza klasą, podając nazwę klasy, następnie operator rozpoznawania zakresu :: , a następnie nazwę konstruktora (która jest taka sama jak klasa):

Przykład

class Car {        // The class
  public:          // Access specifier
    string brand;  // Attribute
    string model;  // Attribute
    int year;      // Attribute
    Car(string x, string y, int z); // Constructor declaration
};

// Constructor definition outside the class
Car::Car(string x, string y, int z) {
  brand = x;
  model = y;
  year = z;
}

int main() {
  // Create Car objects and call the constructor with different values
  Car carObj1("BMW", "X5", 1999);
  Car carObj2("Ford", "Mustang", 1969);

  // Print values
  cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
  cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
  return 0;
}