User Tools

Site Tools


cpp:object_creation

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Next revisionBoth sides next revision
cpp:object_creation [2017/05/10 05:51] – [Παράδειγμα αρχικοποίησης δεικτών] gthanoscpp:object_creation [2018/05/02 10:26] – [Εναλλακτικοί τρόποι κλήσης του κατασκευαστή της κλάσης] gthanos
Line 82: Line 82:
 == Με χρήση του τελεστή = πριν τις αγκύλες == == Με χρήση του τελεστή = πριν τις αγκύλες ==
  
-<code c++>+<code c++ RectangleInitialization.cpp>
 int main () { int main () {
   Rectangle rect = {5,6}; // calls Rectangle(int w, int h)   Rectangle rect = {5,6}; // calls Rectangle(int w, int h)
Line 159: Line 159:
 <code cpp Rectangle.cpp> <code cpp Rectangle.cpp>
 #include <iostream> #include <iostream>
 +#include <cstdlib>
 using namespace std; using namespace std;
  
 class Rectangle { class Rectangle {
   private:   private:
-    int width, height;+    int *width, *height;
   public:   public:
     Rectangle(int w, int h);     Rectangle(int w, int h);
-    Rectangle(int s)+    ~Rectangle();
-    Rectangle(); +
-    int getWidth() const; +
-    int getHeight() const;+
     void setWidth(int w);     void setWidth(int w);
     void setHeight(int h);     void setHeight(int h);
-    int getArea() const;+    int getWidth(); 
 +    int getHeight(); 
 +    int getArea();
 }; };
  
-Rectangle::Rectangle(int w, int h)width(w)height(h) {} +Rectangle::Rectangle(int w, int h) 
-Rectangle::Rectangle(int swidth(s), height(s{+  width = new (nothrowint;     
-Rectangle::Rectangle(): width(0), height(0{}+  height = new (nothrow) int; 
 +  if(width == NULL || height == NULL) { 
 +    cerr << "Memory allocation failure!\n"; 
 +    exit(-1)
 +  } 
 +  *width = w; *height = h; 
 +  cout << "Constructing rectangle (w:"<< *width <<"h:"<<*height<<")\n"; 
 +} 
 + 
 +Rectangle::~Rectangle() 
 +  cout << "Destructing rectangle (w:"<< *width <<"h:"<<*height<<")\n"; 
 +  delete width; 
 +  delete height; 
 +}
  
-int Rectangle::getWidth() const return width;} +void Rectangle::setWidth(int w) { *width = w; } 
-int Rectangle::getHeight() const return height;} +void Rectangle::setHeight(int h) { *height = h; } 
-void Rectangle::setWidth(int w) { width = w; } +int Rectangle::getWidth() { return *width; } 
-void Rectangle::setHeight(int h) { height = h; } +int Rectangle::getHeight() { return *height; } 
-int Rectangle::getArea() const { return width*height;}+int Rectangle::getArea() { return *width *height; }
 </code> </code>
  
cpp/object_creation.txt · Last modified: 2021/05/07 06:22 (external edit)