Home > Article > Backend Development > The relationship between C++ function parameter passing methods and object member functions
C Function parameters can be passed by value or by reference. The parameter passing of object member functions additionally considers the this pointer. By default, the this pointer is passed as an implicit parameter. Non-reference parameters are passed by value by default, and reference parameters implicitly point to this.
C The relationship between function parameter passing methods and object member functions
In C, function parameters are passed in two ways: Pass by value and pass by reference. For object member functions, there are additional considerations for how parameters are passed.
Passing by value
When a parameter is passed by value, the function gets a copy of the parameter. Any modifications made to the copy will not affect the original data.
Pass by reference
When parameters are passed by reference, the function directly accesses the original data. Any modifications made to the parameters in the function will be reflected in the changes to the original data after the function was called.
Parameter passing of object member functions
When the object member function does not accept any parameters, by default, this
pointer will be used as an implicit Parameters passed to member functions. this
The pointer points to the object calling the member function, allowing access and modification of object data.
If an object member function accepts parameters, parameter passing follows the same way as a normal function. However, the following points need to be noted:
this
as if they were this->field
. Practical case
We use an example to illustrate the parameter passing method of object member functions. Suppose we have a Person
class, which has a name
member variable:
class Person { public: string name; void printName() { cout << "Name: " << name << endl; } void changeName(string newName) { name = newName; } };
int main() { Person person; person.name = "John Doe"; string newName = "Jane Doe"; person.changeName(newName); person.printName(); // 输出:Name: Jane Doe // newName 变量不会受到函数调用影响,仍然是 "Jane Doe"。 }
int main() { Person person; person.name = "John Doe"; string& newName = person.name; newName = "Jane Doe"; person.printName(); // 输出:Name: Jane Doe // newName 变量和 name 成员变量都指向同一个地址,因此更改 newName 会影响 name。 }
The above is the detailed content of The relationship between C++ function parameter passing methods and object member functions. For more information, please follow other related articles on the PHP Chinese website!