C++ Tutorial/Class/class definition — различия между версиями

Материал из C\C++ эксперт
Перейти к: навигация, поиск
м (1 версия: Импорт контента...)
 
(нет различий)

Текущая версия на 10:29, 25 мая 2010

classes example

#include <iostream>
#include <stdio.h>
using namespace std;
class Rectangle {
    int x, y;
  public:
    void set_values (int,int);
    int area (void) {return (x*y);}
};
void Rectangle::set_values (int a, int b) {
  x = a;
  y = b;
}
int main () {
  Rectangle rect;
  rect.set_values (3,4);
  cout << "area: " << rect.area();
  return 0;
}
area: 12"

Class objects can be assigned to each other using default memberwise assignment

#include <iostream>
using std::cout;
using std::endl;
class Date 
{
public:
   Date( int = 1, int = 1, int = 2007 );
   void print();
private:
   int month;
   int day;
   int year;
};
Date::Date( int m, int d, int y )
{
   month = m;
   day = d;
   year = y;
}
void Date::print() 
{ 
   cout << month << "/" << day << "/" << year; 
}
int main()
{
   Date date1( 8, 8, 2008 );
   Date date2;
   cout << "date1 = ";
   date1.print();
   cout << "\ndate2 = ";
   date2.print();
   date2 = date1;
   cout << "\n\nAfter default memberwise assignment, date2 = ";
   date2.print();
   cout << endl;
   return 0;
}
date1 = 8/8/2008
date2 = 1/1/2007
After default memberwise assignment, date2 = 8/8/2008

containership with employees and degrees

#include <iostream>  
  #include <string>  
  using namespace std;  
  class student{  
     private:  
        string school; 
        string degree; 
     public:  
        void getedu(){  
           cout << "   Enter name of school or university: ";  
           cin >> school;  
           cout << "   Enter highest degree earned \n";  
           cout << "   (Highschool, Bachelor"s, Master"s, PhD): ";  
           cin >> degree;  
        }  
        void putedu() const{  
           cout << "\n   School or university: " << school;  
           cout << "\n   Highest degree earned: " << degree;  
        }  
  };  
  class employee{  
     private:  
        string name; 
        unsigned long number;  
     public:  
        void getdata(){  
           cout << "\n   Enter last name: "; cin >> name;  
           cout << "   Enter number: ";      cin >> number;  
        }  
        void putdata() const{  
           cout << "\n   Name: " << name;  
           cout << "\n   Number: " << number;  
        }  
  };  
  class manager{  
     private:  
        string title;   
        double dues;    
        employee emp;   
        student stu;    
     public:  
        void getdata(){  
           emp.getdata();  
           cout << "   Enter title: ";          cin >> title;  
           cout << "   Enter golf club dues: "; cin >> dues;  
           stu.getedu();  
        }  
        void putdata() const{  
           emp.putdata();  
           cout << "\n   Title: " << title;  
           cout << "\n   Golf club dues: " << dues;  
           stu.putedu();  
        }  
  };  
  class scientist{  
     private:  
        int pubs;
        employee emp;
        student stu; 
     public:  
        void getdata(){  
           emp.getdata();  
           cout << "   Enter number of pubs: "; cin >> pubs;  
           stu.getedu();  
        }  
        void putdata() const{  
           emp.putdata();  
           cout << "\n   Number of publications: " << pubs;  
           stu.putedu();  
        }  
    };  
  class laborer{  
     private:   
        employee emp;
     public:  
        void getdata(){ emp.getdata(); }  
        void putdata() const{ emp.putdata(); }  
  };  
  int main()  
  {  
     manager m1;  
     scientist s1, s2;  
     laborer l1;  
    
     cout << endl;  
     cout << "\nEnter data for manager 1";    
     m1.getdata();                            
    
     cout << "\nEnter data for scientist 1";  
     s1.getdata();  
    
     cout << "\nEnter data for scientist 2";  
     s2.getdata();  
    
     cout << "\nEnter data for laborer 1";  
     l1.getdata();  
    
     cout << "\nData on manager 1";           
     m1.putdata();                            
    
     cout << "\nData on scientist 1";  
     s1.putdata();  
    
     cout << "\nData on scientist 2";  
     s2.putdata();  
    
     cout << "\nData on laborer 1";  
     l1.putdata();  
     cout << endl;  
     return 0;  
  }

Create an object from a Class and call its function

#include <iostream>
using std::cout;
using std::endl;
class MyClass
{
public:
   void displayMessage()
   {
      cout << "Welcome!" << endl;
   } 
};
int main()
{
   MyClass obj; 
   obj.displayMessage(); 
   return 0;
}
Welcome!

Define a class with a member function that takes a parameter

#include <iostream>
using std::cout; 
using std::cin;
using std::endl;
#include <string> 
using std::string;
using std::getline;
class MyClass
{
public:
   void displayMessage( string n )
   {
      cout << "Welcome \n" << n << "!" 
         << endl;
   } 
};
int main()
{
   string name; 
   MyClass obj;
   
   cout << "Please enter the name:" << endl;
   getline( cin, name );
   cout << endl;
   obj.displayMessage( name );
   return 0; 
}
Please enter the name:
Joe
Welcome
Joe!

Define class to record time

#include <iomanip>
#include <iostream>
using std::cout;
using std::endl;
using std::setfill;
using std::setw;
class Time 
{
public:
   Time(); 
   void setTime( int, int, int );
   void printUniversal();
   void printStandard();
private:
   int hour;
   int minute;
   int second;
};
Time::Time() 
{ 
   hour = minute = second = 0; 
}
void Time::setTime( int h, int m, int s )
{
   hour = h ;
   minute = m;
   second = s ;
}
void Time::printUniversal()
{
   cout << setfill( "0" ) << setw( 2 ) << hour << ":" << setw( 2 ) << minute << ":" << setw( 2 ) << second;
}
void Time::printStandard()
{
   cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour " 
      << setfill( "0" ) << setw( 2 ) << minute << ":" << setw( 2 )
      << second << ( hour < 12 ? " AM" : " PM" );
}
int main()
{
   Time t; 
   t.printUniversal();
   t.printStandard(); 
   t.setTime( 1, 2, 6 ); 
   t.printUniversal();
   t.printStandard(); 
   t.setTime( 99, 99, 99 ); 
   t.printUniversal();
   t.printStandard();
   return 0; 
}
00:00:0012:00:00 AM01:02:061:02:06 AM99:99:993:99:99 PM

Define class with a data member and member functions to set and get its value

#include <iostream>
using std::cout; 
using std::cin;
using std::endl;
#include <string>
using std::string;
using std::getline;
class MyClass
{
public:
   void setName( string name )
   {      
      name = name; 
   }
   
   string getName() 
   {
      return name; 
   } 
   void displayMessage()
   {
      cout << "Welcome to the grade book for\n" << getName() << "!" << endl;
   } 
private:
   string name; 
};
int main()
{
   string n; 
   MyClass obj;
   
   cout << "Initial name is: " << obj.getName() << endl;
   cout << "\nPlease enter the name:" << endl;
   getline( cin, n );
   obj.setName( n );
   cout << endl;
   obj.displayMessage();
   return 0;
}
Initial name is:
Please enter the name:
Joe
Welcome to the grade book for
!

Define your first class

#include <iostream> 
using namespace std; 
 
 
class ThreeDimension {  
public: 
  int X;   
  int Y;     
  int Z;         
}; 
  
int main() {  
  ThreeDimension myDimension;  
  int range;  
 
  // Assign values to fields in myDimension. 
  myDimension.X = 7; 
  myDimension.Y = 16; 
  myDimension.Z = 21; 
  
  // Compute the range assuming a full tank of gas. 
  range = myDimension.Y * myDimension.Z; 
  
  cout << range;  
 
  return 0; 
}
336

Friend Classes

#include <iostream>
using namespace std;
   
class TwoValues {
  int a;
  int b;
public:
  TwoValues(int i, int j) { a = i; b = j; }
  friend class Min;
};
   
class Min {
public:
  int min(TwoValues x);
};
   
int Min::min(TwoValues x)
{
  return x.a < x.b ? x.a : x.b;
}
   
int main()
{
  TwoValues ob(10, 20);
  Min m;
   
  cout << m.min(ob);
   
  return 0;
}

Inner class

#include <iostream>
using namespace std;
class Outer 
{
 public:
   Outer(void) 
   { cout << "Just instantiated an outer\n"; 
     outer_data = 2002; 
   };
   class Inner 
   {
     public:
       Inner(void) 
     { 
       cout << "Just instantiated an inner\n"; 
           inner_data = 1001; 
     };
       void show_data(void) { cout << "Inner: " << inner_data << endl; };
     private:
       int inner_data;
   } inside_stuff; 
   void show_all_data(void) 
   { 
     inside_stuff.show_data(); 
       cout << "Outer: " << outer_data << endl; 
   };
 private:
   int outer_data;
};
int main(void)
{
   Outer my_data;
   my_data.show_all_data();
}

Instantiating multiple objects of the class using its constructor

#include <iostream>
using std::cout; 
using std::endl;
#include <string>
using std::string;
class MyClass
{
public:
   MyClass( string name )
   {
      setName( name ); 
   } 
   void setName( string n )
   {
      name = n;
   } 
   string getName()
   {
      return name; 
   } 
   void displayMessage()
   {
      cout << "Welcome " << getName()  << "!" << endl;
   }
private:
   string name;
};
int main()
{
   MyClass obj1( "A" );
   MyClass obj2( "B" );
   cout << obj1.getName()<< "\n" << obj2.getName() << endl;
   return 0;
}
A
B

Local Classes: A class may be defined within a function

#include <iostream>
using namespace std;
   
void f();
   
int main()
{
  f();
  return 0;
}
   
void f()
{
  class myclass {
    int i;
  public:
    void put_i(int n) { i=n; }
    int get_i() { return i; }
  } ob;
   
  ob.put_i(10);
  cout << ob.get_i();
}