Cpp: "->" and the difference. ""

environments:gcc version 8.1.0 (x86_64-posix-seh-rev0, Built by MinGW-W64 project)

 

class data{

public:

  int x;

  data(int vx):vx(x){}

  void msg(){}

};

 

// create class data instances;

data d = data(3);

data* cpt = &d;

d.msg();

cpt->msg();

 

typedef  struct col{

  collection(int id, float score):cid{id},cscore{score}{}

  int cid;

  float cscore;

} collection;

 

// create struct col object

collection c{1,145.3};

cout << c.cid << endl ;

cout << c.cscore <<endl;

 

collection* spt = &c;

cout << spt -> cid << endl;

cout << spt-> cscore << endl;

 

 

"." Cpp and "->" Explanation:

  1, is a member of the operator, for the transfer of member variables and member functions. "";. "" Symbol on the left must be an instance of an object (specific object), for example green font;

  2, "->" is the address operator is used to reference the member variables and member functions; the symbol "->" to the left is the instance of the object address or a class name (name structure), for example as a yellow font;

  3, equivalents: d.msg () and (* cpt) .msg () equivalent; c.cid and (* spt) .cid;

  . "" 4, and "->" used in " class and Structure " related operations;

  5, the structure described initialization: Portal

 

 

 

The following is a specific code:

 1 #include<iostream>
 2 
 3 using namespace std;
 4 
 5 
 6 class Info{
 7 
 8 private:
 9     int iage;
10     int iid;
11 
12 public:
13     Info(int age, int id):iage(age),iid(id){}
14     void msg(){
15         cout << "age = " << this->iage << "\t";
16         cout << "id = " << this->iid << endl;
17     }
18 
19 };
20 
21 
22 typedef    struct Data
23 {
24     Data(int id, float math):did{id},dmath{math}{}
25     float dmath;
26     int did;
27 } data;
28 
29 
30 
31 int main(){
32 
33     Info information = Info(30, 1);
34     Info* cpt;
35     information.msg();
36     cpt = &information;
37     cpt -> msg();
38 
39 
40     data d{1,145};
41     cout <<"d.id = " << d.did << "\t";
42     cout <<"d.math = " << d.dmath << endl;
43 
44     data* spt;
45     spt = &d;
46     cout <<"spt->id = " << spt->did << "\t";
47     cout <<"spt->math = " << spt->dmath << endl;
48 
49     return 0;
50 }
51 
52 // result:
53 // age = 30        id = 1
54 // age = 30        id = 1
55 // d.id = 1        d.math = 145
56 // spt->id = 1     spt->math = 145

 

Guess you like

Origin www.cnblogs.com/lnlidawei/p/12002817.html