1.结构体参数传递:相当于复制一份,浪费空间
struct Base
{
int x;
int y;
int z;
};
void function(Base b){}
int main(int argc, char* argv[])
{
Base base;
function(base);
return 0;
}
2.结构体指针参数传递:只传结构体首地址,节省空间
struct Base
{
int x;
int y;
};
int Max(Base* pb)
{
if (pb->x > pb->y)
{
return pb->x;
}
else
{
return pb->y;
}
}
int main(int argc, char* argv[])
{
Base base;
base.x = 1;
base.y = 2;
Max(&base);
return 0;
}
3.函数在结构体内部
struct Base
{
int x;
int y;
int Max(Base* pb)
{
if (pb->x > pb->y)
{
return pb->x;
}
else
{
return pb->y;
}
}
};
int main(int argc, char* argv[])
{
Base base;
base.x = 10;
base.y = 20;
base.Max(&base);
return 0;
}
思考:只有一个参数,为什么传了2个值
答案:当函数在结构体内部时,会默认传该结构体的首地址。
4.探究:默认传入的ecx到底是不是结构体的首地址?
struct Base
{
int x;
int y;
int Max()
{
if (x > y)
{
return x;
}
else
{
return y;
}
}
};
int main(int argc, char* argv[])
{
Base base;
base.x = 10;
base.y = 20;
int a = base.Max();
printf("%d",a);
return 0;
}
很显然 传入的ecx就是结构体的首地址
5.在C++中,上面的ecx的值即为this指针
this指针特点如下:
- 你用或者不用,它就在那里
- 参数个数确定的时候,用ecx来传递
- 参数个数不确定的时候,最后一个传递(参见不定长参数)
- this指针不能做++ – 等运算,不能重新被赋值.
- this指针不占用结构体的宽度.
6.Summary
- 在底层中,C++对于C来说,多了2个++,这个++是由编译器来实现,你用它的语法,它就会帮你添加一些代码,学习C++要搞懂编译器做了什么,怎么使你的编程更方便
- 函数在结构体内部也不占用结构体的空间,函数归属于某个结构体是对于编译器而言,不加上Base.编译器就无法找到对应的函数,但对于底层而言,它只是个函数,跟其他函数一样的存在方式,一样的call,仅仅多传了一个this指针用于方便你的操作
- 封装: 1、将函数定义到结构体内部,就是封装.
2、编译器会自动传递结构体的指针给函数. - 类:带有函数的结构体,称为类.
- 成员函数:结构体里面的函数,称为成员函数.