Cpp:"->"和"."的区别

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中“.”和“->”说明:

  1、“.”是成员运算符,用于调取成员变量和成员函数;符号“.”的左边必须是实例对象(具体对象),举例为绿色字体;

  2、“->”是地址运算符,用于引用成员变量和成员函数;符号“->”的左边实例对象的地址或者类名(结构名),举例为黄色字体;

  3、等价形式:d.msg() 和 (*cpt).msg() 等价;c.cid 和 (*spt).cid;

  4、“.”和“->”常用于“类和结构”相关操作;

  5、结构体初始化说明:传送门

下面是具体代码:

 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 << "	";
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 << "	";
42     cout <<"d.math = " << d.dmath << endl;
43 
44     data* spt;
45     spt = &d;
46     cout <<"spt->id = " << spt->did << "	";
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
本文由lnlidawei(https://www.cnblogs.com/lnlidawei)原创或整理,转载请注明出处。
原文地址:https://www.cnblogs.com/lnlidawei/p/12002817.html