C++/Class/Constructor

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Call constructor from base class

<source lang="cpp">

  1. include <iostream>

using namespace std; class IntPair { public:

 int a;
 int b;
 IntPair(int i, int j) : a(i), b(j) { }

}; class MyClass {

 IntPair nums;

public:

 // Initialize nums object using initialization syntax.
 MyClass(int x, int y) : nums(x,y) { }
 int getNumA() { 
    return nums.a; 
 }
 int getNumB() { 
    return nums.b; 
 }

}; int main() {

 MyClass object1(7, 9), object2(5, 2);
 cout << "Values in object1 are " << object1.getNumB() <<
         " and " << object1.getNumA() << endl;
 cout << "Values in object2 are " << object2.getNumB() <<
         " and " << object2.getNumA() << endl;
 return 0;

}


 </source>


Constructing and Destructing sequence for three level inheritance

<source lang="cpp">

  1. include <iostream>

using namespace std; class BaseClass { public:

 BaseClass() { 
    cout << "Constructing base\n"; 
 }
 ~BaseClass() { 
     cout << "Destructing base\n"; 
 }

}; class DerivedClass1 : public BaseClass { public:

 DerivedClass1() { 
    cout << "Constructing DerivedClass1\n"; 
 }
 ~DerivedClass1() { 
     cout << "Destructing DerivedClass1\n"; 
 }

}; class DerivedClass2: public DerivedClass1 { public:

 DerivedClass2() { 
    cout << "Constructing DerivedClass2\n"; 
 }
 ~DerivedClass2() { 
    cout << "Destructing DerivedClass2\n"; 
 }

}; int main() {

 DerivedClass2 ob;
 return 0;

}



 </source>


Constructor: different parameter type

<source lang="cpp">

  1. include <iostream>
  2. include <cstdlib>

using namespace std; class myclass {

 int a;

public:

 myclass(int x) { 
    a = x; 
 } 
 myclass(char *str) { 
    a = atoi(str); 
 }
 int geta() { 
    return a; 
 }

};

int main() {

 myclass object1 = 4;     
 myclass object2 = "123"; 
 cout << "object1: " << object1.geta() << endl;
 cout << "object2: " << object2.geta() << endl;
 return 0;

}



 </source>


Constructor with 2 parameters

<source lang="cpp">

  1. include <iostream>

using namespace std; class MyClass {

 int h;
 int i;

public:

 MyClass(int j, int k) { 
    h = j; 
    i = k; 
 } 
 int getInt() {
    return i;
 }
 int getHeight() {
    return h;
 }

}; int main() {

 MyClass myObject[3] = {
   MyClass(1, 2), // initialize
   MyClass(3, 4),
   MyClass(5, 6)
 };
 int i;
 for(i=0; i<3; i++) {
   cout << myObject[i].getHeight();
   cout << ", ";
   cout << myObject[i].getInt() << "\n";
 }
 return 0;

}



 </source>


Constructor with parameter value checking

<source lang="cpp">

  1. include <iostream>
  2. include <iomanip>
  3. include <string.h>
  4. include <stdlib.h>

using namespace std; class Book {

 public: 
   char *title;
   char *author;
   float price;
   Book(char *title, char *author, char *publisher, float price);
   void show_title(void) { cout << title << "\n"; };
   float get_price(void) { return(price); };
   void show_book(void) 
   { 
     show_title(); 
     show_publisher(); 
   };
   void assign_publisher(char *name) { strcpy(publisher, name); };
 private:
   char *publisher;
   void show_publisher(void) { cout << publisher << "\n"; };

}; Book::Book(char *title, char *author, char *publisher, float price)

{
  if ((Book::title = new char[256]) == 0)
    {
      cerr << "Error allocating memory\n";
      exit(0);
    }
  if ((Book::author = new char[64]) == 0)
    {
      cerr << "Error allocating memory\n";
      exit(0);
    }
  if ((Book::publisher = new char[128]) == 0)
    {
      cerr << "Error allocating memory\n";
      exit(0);
    }
  strcpy(Book::title, title);
  strcpy(Book::author, author);
  strcpy(Book::publisher, publisher);
  Book::price = price;
}

int main(void)

{
  Book tips("A", "B", "B",49.95);
  Book diary("C", "D", "D", 9.95);
  tips.show_book();
  diary.show_book();
}
 
   
   
 </source>


Define constructor outside a class definition

<source lang="cpp">

  1. include <iostream>
  2. include <iomanip>
  3. include <string.h>

using namespace std; class Book {

 public: 
   char title[256];
   char author[64];
   float price;
   Book(char *btitle, char *bauthor, char *bpublisher, float bprice);
   void show_title(void) { cout << title << "\n"; };
   float get_price(void) { return(price); };
   void show_book(void) 
   { 
     show_title();
     show_publisher();
   };
   void assign_publisher(char *name) { strcpy(publisher, name); };
 private:
   char publisher[256];
   void show_publisher(void) { cout << publisher << "\n"; };

}; Book::Book(char *btitle, char *bauthor, char *bpublisher, float bprice) {

  strcpy(title, btitle);
  strcpy(author, bauthor);
  strcpy(publisher, bpublisher);
  price = bprice;

} int main(void) {

  Book tips("A", "B", "C", 49.95);
  Book diary("D", "E", "F", 9.95);
  tips.show_book();
  diary.show_book();

}


 </source>


overloading class constructors

<source lang="cpp">

  1. include <iostream>

using namespace std; class CRectangle {

   int width, height;
 public:
   CRectangle ();
   CRectangle (int,int);
   int area (void) {return (width*height);}

}; CRectangle::CRectangle () {

 width = 5;
 height = 5;

} CRectangle::CRectangle (int a, int b) {

 width = a;
 height = b;

} int main () {

 CRectangle rect (3,4);
 CRectangle rectb;
 cout << "rect area: " << rect.area() << endl;
 cout << "rectb area: " << rectb.area() << endl;
 return 0;

}


 </source>


Parameterized Constructors

<source lang="cpp">

  1. include <iostream>

using namespace std; class myclass {

 int a, b;

public:

 myclass(int i, int j) {
    a=i; 
    b=j;
 }
    
 void show() {
    cout << a << " " << b;
 }

}; int main() {

 myclass ob(3, 5);
 ob.show();
 return 0;

}


 </source>


string type constructor

<source lang="cpp">

  1. include <iostream>
  2. include <cstring>
  3. include <cstdlib>

using namespace std; class StringClass {

 char *p;
 int len;

public:

 StringClass(char *ptr);
 ~StringClass();
 void show();

}; StringClass::StringClass(char *ptr) {

 len = strlen(ptr);
 p = new char [len+1];
 if(!p) {
   cout << "Allocation error\n";
   exit(1);
 }
 strcpy(p, ptr);

} StringClass::~StringClass() {

 cout << "Freeing p\n";
 delete [] p;

} void StringClass::show() {

 cout << p << " - length: " << len;
 cout << endl;

} int main() {

 StringClass stringObject1("www.java2s.com"), stringObject2("www.java2s.com");
 stringObject1.show();
 stringObject2.show();
 return 0;

}



 </source>


Use automatic conversions to assign new values

<source lang="cpp">

  1. include <iostream>
  2. include <cstdlib>

using namespace std; class myclass {

 int a;

public:

 myclass(int x) { 
    a = x; 
 } 
 myclass(char *str) { 
    a = atoi(str); 
 }
 int geta() { 
    return a; 
 }

};

int main() {

 myclass object1 = 4;     // converts to myclass(4)
 myclass object2 = "123"; // converts to myclass("123");
 cout << "object1: " << object1.geta() << endl;
 cout << "object2: " << object2.geta() << endl;
 
 object1 = "1776";        // converts into object1 = myclass("1776");
 object2 = 2001;          // converts into object2 = myclass(2001);
 cout << "object1: " << object1.geta() << endl;
 cout << "object2: " << object2.geta() << endl;
 return 0;

}



 </source>


Use constructor to init member variables

<source lang="cpp">

  1. include <iostream>

using namespace std; class myclass {

 int i, j;

public:

 myclass(int x, int y) { 
   i = x; 
   j = y; 
 }
 void show() { 
   cout << i << " " << j; 
 }

}; int main() {

 myclass count(2, 3);
 count.show();
 return 0;

}


 </source>


Use Double value as the constructor parameter

<source lang="cpp">

  1. include <iostream>

using namespace std; class MyClass {

 double l, w, h;
 double volume;

public:

 MyClass(double a, double b, double c);
 void vol();

}; MyClass::MyClass(double a, double b, double c) {

 l = a;
 w = b;
 h = c;
 volume = l * w * h;

} void MyClass::vol() {

 cout << "Volume is: " << volume << endl;

} int main() {

 MyClass x(2.2, 3.97, 8.09), y(1.0, 2.0, 3.0);
 x.vol();
 y.vol();
 return 0;

}


 </source>