提问人:AnveK 提问时间:4/7/2021 更新时间:4/7/2021 访问量:101
为什么成员函数不像 c++ 中的普通函数那样按值调用?
Why aren't the member functions called by value like the normal functions in c++?
问:
在 c++ 中,如果出现以下情况,则对函数内参数所做的更改不会反映在实际变量中
函数的返回值是无效的,但成员函数并非如此,我们可以
在成员函数中看到永久发生的更改。
#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;
}
答:
-2赞
dspeyer
4/7/2021
#1
因为你没有改变一个论点。您的示例函数不接受任何参数。您正在更改成员变量。
您可以将对象的所有成员视为自动传递的引用参数,但这不是 C++ 鼓励您考虑它们的方式。
评论
0赞
AnveK
4/7/2021
非常感谢,我理解了这个概念。
1赞
Remy Lebeau
4/7/2021
#2
在 c++ 中,如果函数的返回值为 void,则对函数内部参数所做的更改不会反映在实际变量中
对参数值的更改与函数的返回类型完全无关。void 函数可以很容易地对其参数进行更改。这些更改是否反映回调用方与参数是否通过指针/引用传递有关。
但成员函数并非如此,我们可以看到永久发生的变化。
非静态类方法接收指向正在调用它的对象的隐藏指针。当该方法访问其所属类的非静态成员时,它将使用该指针来访问该成员。因此,对成员所做的任何更改都将直接对 mmeber 完成。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;
}
评论