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 revisionBoth sides next revision
cpp:object_creation [2017/05/10 05:51] – [Παράδειγμα αρχικοποίησης δεικτών] gthanoscpp:object_creation [2018/05/02 08:35] – [Παράδειγμα αρχικοποίησης δεικτών] gthanos
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 s) : width(s), height(s{+  width = new (nothrowint;     
-Rectangle::Rectangle(): width(0), height(0{}+  height = new (nothrowint; 
 +  if(width == NULL || height == NULL
 +    cerr << "Memory allocation failure!\n"; 
 +    exit(-1)
 +  
 +  *width = w; *height = h; 
 +  cout << "Constructing rectangle (w:"<< *width <<"h:"<<*height<<")\n"; 
 +}
  
-int Rectangle::getWidth() const return width;} +Rectangle::~Rectangle() { 
-int Rectangle::getHeight(const { return height;} +  cout << "Destructing rectangle (w:"<< *width <<", h:"<<*height<<")\n"; 
-void Rectangle::setWidth(int w) { width = w; } +  delete width; 
-void Rectangle::setHeight(int h) { height = h; } +  delete height; 
-int Rectangle::getArea() const { return width*height;}+} 
 + 
 +void Rectangle::setWidth(int w) { *width = w; } 
 +void Rectangle::setHeight(int h) { *height = h; } 
 +int Rectangle::getWidth() { return *width; } 
 +int Rectangle::getHeight() { return *height; } 
 +int Rectangle::getArea() { return *width *height; }
 </code> </code>
  
cpp/object_creation.txt · Last modified: 2021/05/07 06:22 (external edit)