首页 > 解决方案 > 为什么成员函数不像 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++classobjectoopcall-by-value

解决方案


在 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;
}

推荐阅读