Aquí hay un ejemplo que muestra cómo usar la función constructora en C ++.
#include <iostream> using namespace std; class Car { public: int number; // a construct without parameter Car(){ number = 123; //assign a default value } // a construct with parameter Car(int x){ number = x; } void Create() { cout << "Car created, number is: " << number << "n" ; } }; int main() { Car x(456); //equals to Car *z = new Car(63746); x.Create(); Car y; y.Create(); Car *z; z = new Car(789); z->Create(); } |
Si no se define ningún constructor, puede usar Car x = {123456};
#include <iostream> using namespace std; class Car { public: int number; void Create() { cout << "Car created, number is: " << number << "n" ; } }; int main() { Car x = {123456}; x.Create(); Car *y = new Car(); y->Create(); } |