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* cpt = &c;
cout << cpt -> cid << endl;
cout << cpt -> cscore << endl;
Cpp中“.”和“->”说明:
1、“.”是成员运算符,用于调取成员变量和成员函数;符号“.”的左边必须是实例对象(具体对象),应用实例为绿色字体;
2、“->”是地址运算符,用于引用成员变量和成员函数;符号“->”的左边是实例对象的地址或者类名(结构名);
3、“.”和“->”常用于“类和结构”相关操作;
4、结构体初始化说明:传送门
下面是具体代码:
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