C++笔记

来源:互联网 发布:球员对比的软件 编辑:程序博客网 时间:2024/06/03 21:55

C++ Classes & Objects

class Box{   public:      double length;   // Length of a box      double breadth;  // Breadth of a box      double height;   // Height of a box};
关键字public可在类外访问。

Box Box1;          // Declare Box1 of type BoxBox Box2;          // Declare Box2 of type Box
对象是创建于类。Box1和Box2均有Box类的数据成员函数。

下面通过具体的例子来说明如何访问数据成员:

#include <iostream> using namespace std; class Box{   public:      double length;   // Length of a box      double breadth;  // Breadth of a box      double height;   // Height of a box}; int main( ){   Box Box1;        // Declare Box1 of type Box   Box Box2;        // Declare Box2 of type Box   double volume = 0.0;     // Store the volume of a box here    // box 1 specification   Box1.height = 5.0;    Box1.length = 6.0;    Box1.breadth = 7.0;    // box 2 specification   Box2.height = 10.0;   Box2.length = 12.0;   Box2.breadth = 13.0;   // volume of box 1   volume = Box1.height * Box1.length * Box1.breadth;   cout << "Volume of Box1 : " << volume <<endl;    // volume of box 2   volume = Box2.height * Box2.length * Box2.breadth;   cout << "Volume of Box2 : " << volume <<endl;   return 0;}
ConceptDescription

Class member functions

A member function of a class is a function that has its definition or its prototype within the class definition like any other variable.

Class access modifiers

A class member can be defined as public, private or protected. By default members would be assumed as private.

Constructor & destructor

A class constructor is a special function in a class that is called when a new object of the class is created. A destructor is also a special function which is called when created object is deleted.

C++ copy constructor

The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously.

C++ friend functions

friend function is permitted full access to private and protected members of a class.

C++ inline functions

With an inline function, the compiler tries to expand the code in the body of the function in place of a call to the function.

The this pointer in C++

Every object has a special pointer this which points to the object itself.

Pointer to C++ classes

A pointer to a class is done exactly the same way a pointer to a structure is. In fact a class is really just a structure with functions in it.

Static members of a class

Both data members and function members of a class can be declared as static.

0 0
原创粉丝点击