c++ - 为什么成员函数不像 c++ 中的普通函数那样按值调用?
问题描述
在 C++ 中,如果函数的返回值为 void,则对函数内部参数所做的更改不会反映在实际变量中,但成员函数并非如此,我们可以
看到永久发生的更改。
#include<iostream>
using namespace std;
class Student {
public:
int age;
float marks;
Student()
{
cout << "call by default";
}
void ageInc()
{
age = age + 1;
}
};
int main()
{
Student s;
s.age = 34;
cout << s.age << endl;
s.ageInc();
cout << s.age << endl;
return 0;
}
解决方案
在 C++ 中,如果函数的返回值为 void,则对函数内部参数所做的更改不会反映在实际变量中
对参数值的更改与函数的返回类型完全无关。一个 void 函数可以很容易地改变它的参数。这些更改是否反映回调用者与参数是否通过指针/引用传递有关。
但成员函数并非如此,我们可以看到永久发生的变化。
一个非静态类方法接收一个指向它被调用的对象的隐藏指针。 this
当该方法访问其所属类的非静态成员时,它使用该this
指针来访问该成员。因此,对成员所做的任何更改都直接对成员进行。
您的示例大致相当于幕后的以下内容:
#include <iostream>
using namespace std;
struct Student {
int age;
float marks;
};
Student_ctr(Student* const this)
{
cout << "call by default";
}
Student_dtr(Student* const this) {}
void Student_ageInc(Student* const this)
{
this->age = this->age + 1;
}
int main()
{
Student s;
Student_ctr(&s);
s.age = 34;
cout << s.age << endl;
Student_ageInc(&s);
cout << s.age << endl;
Student_dtr(&s);
return 0;
}
推荐阅读
- android - 我如何从任何健康乐队获取卡路里数据?
- c++ - 在循环条件下处理 size_t 下溢的成语
- gremlin - 有没有办法在 asyncio Python 应用程序中使用 Gremlin?
- user-interface - 如何在代号1的UI界面下面设计这个
- database - 将服装数据库与 WP 数据库合并
- batch-file - 在目录中搜索文件列表时无法将值动态存储在批处理文件中
- javascript - 如何根据用户选择在 ASP.NET Core MVC 的不同下拉菜单中填充下拉菜单?
- react-native - 如何在 jhipster 中自定义 react-navigation 而不是 react-native-navigation?
- r - 在 R 中调整 plotmo::plot_glmnet 的顶轴标题和标签图
- python - 如何修复 ValueError:字典更新序列元素 #0 的长度为 1;需要 2 odoo 12?