【C++】Classes and Objects

    【C++】Classes and Objects

        1. Definition of  a class

        two. Definition and use of objects

 refer to:

"C++ from entry to proficient" People's Posts and Telecommunications Publishing House

 

First, distinguish between the following declarations and definitions.

    Statement : is to introduce the name to the computer, that is, what the name means.

    Definition : is to allocate memory space for this name.

 

1. Definition of a class

The definition of a class is divided into two parts: the declaration part of the class and the implementation of the class.

          Class declaration : declares the members (member data and member functions) in the class.

          Class implementation : used to define member functions, which are used to operate on member data.

The class definition has the form:

            

    Class members have three access rights:

    (1) public (public) : can be accessed outside the class

    (2) private (private) : the member can only be accessed by member functions of the class

    (3) protected (protected) : the member can only be accessed by the member function of the class or the member function of the derived class

    Among them, data members are usually private, and member functions are public and private. Public member functions can be accessed outside the class, also known as the class interface .

 

two. Definition and use of objects

    A class is a user-defined data type (which does not occupy memory), and an object is an instance of a class (which occupies a memory unit) .

    An object is an instance of a class, and an object belongs to a known class. Therefore, before defining an object, you must first define a class.

    For example, if you define a Cdate class before, you can define a Cdate object, as follows:

  Cdate d; //Object definition

    A member of an object is a member of the object's class, which contains member data and member functions. Then you can use "." (member operator) to use member variables and functions.

d.setDate(2018,5,6);
 d.print();

The complete procedure is as follows:

//class definition.cpp
#include<iostream>
using namespace std;

//class definition
class Cdate
{
	public:
		void setDate(int x,int y,int z); //Member function declaration
		void print(); //Member function declaration
	private:
		int year,month,day; //Member data declaration
};

// implementation of member functions
void Cdate::setDate(int x,int y,int z)
{
	year=x;
	month=y;
	day=z;
}
// implementation of member functions
void Cdate:: print()
{
	cout<<year<<" "<<month<<" "<<day<<endl;
}


intmain()
{
	Cdate d; //Object definition
	d.setDate(2018,5,6); //The object uses member functions
	d.print();

	return 0;
}

operation result:

    

-------------------------------------------         END      -------------------------------------

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325817939&siteId=291194637