C Functions can return a reference or pointer as a return value in the following ways: Returning a reference: Using '&' as the return type allows the function to modify the value of the caller object. Return pointer: Using '*' as the return type allows the function to modify the value pointed to by the caller object. When using references or pointers, ensure that the object remains valid after the function returns, and avoid unnecessary use that reduces code clarity.
In C, functions usually pass parameters through objects or variables provided by the caller. However, there are situations where you may want a function to return a reference or pointer to the caller object. This can be achieved in several ways.
To return a reference, use the &
return type of the reference. For example:
int& max(int& a, int& b) { return (a > b) ? a : b; }
This function returns a reference to a larger number, allowing the caller to modify the original value.
Suppose we have a student class that contains a name
attribute. We can write a function that returns a reference to the student's name as follows:
class Student { public: string& getName() { return name; } private: string name; }; int main() { Student student; student.getName() = "John Doe"; cout << student.getName() << endl; // 输出:"John Doe" }
To return a pointer, use the *
dereference operator as the return type . For example:
int* max(int* a, int* b) { return (a > b) ? a : b; }
This function returns a pointer to a larger number, allowing the caller to modify the original value.
Suppose we have a shape class that contains an area
attribute. We can write a function that returns a pointer to the area of a shape as follows:
class Shape { public: double* getArea() { return &area; } private: double area; }; int main() { Shape shape; *shape.getArea() = 100.0; cout << *shape.getArea() << endl; // 输出:"100" }
The above is the detailed content of How does a C++ function return a reference or pointer as return value?. For more information, please follow other related articles on the PHP Chinese website!