C + + has many advantages over C, mainly embodied in encapsulation (encapsulation), Inheritance (inheritance) and polymorphism (polymorphism). Encapsulation is the combination of data and operational data functions, not only make the program structure more compact, and improve the security of the internal data of the class, inheritance increases the scalability of the software and code reuse, polymorphism allows designers to design the program can be more abstract, conducive to code maintenance and reusability.
In C, we can define a struct type and wrap multiple related variables into one overall use. Variables in structs can be of the same, partially identical, or completely different types of data. In the C language, structs cannot contain functions. In C + +, structs can contain functions.
Definition of 2.1.1 Structure
#include <iostream>using namespace Std; struct point{ int X; int y;}; int main () {Point pt; Pt.x = 0 ; Pt.y = 0 ; cout <<pt.x<< " <<pt.y<<ENDL; return 0 ;}
Note that when defining a struct, be sure not to forget to add a semicolon to the right curly brace.
Below, the output function is written in the struct, and the code becomes:
#include <iostream>using namespacestd;structpoint{intx; inty; voidoutput () {cout<<x<<" "<<y<<Endl; } };intMain () {Point pt; Pt.x=0; Pt.y=0; Pt.output (); return 0;}
2.1.2 Structure and class
Replace the key struct in the above point struct definition with class, as follows:
class point{ int x; int y; void output () { cout<<x<<""<<y<<Endl; };
By default, struct members are public, and the members of a class are private. In a class, a public member can be accessed outside the class, and the private can only be accessed within the class. As a result, the code in 2.1.1 will simply change the struct to class and then run with an error because we have access to the private members of the class.
Therefore, it can be run if it is changed to public.
#include <iostream>using namespacestd;classpoint{ Public: intx; inty; voidoutput () {cout<<x<<" "<<y<<Endl; } };intMain () {Point pt; Pt.x=0; Pt.y=0; Pt.output (); return 0;}
Chapter II Mastering C + + (1) from structure to class