|  | 
 
 发表于 2023-5-18 07:55:37
|
显示全部楼层 
| 在函数中使用return语句时,可以选择返回函数对象本身或返回函数的值。两者之间的区别在于返回值的类型和函数的使用方式。 
 如果函数返回函数对象本身,则返回的是指向该函数的指针或引用。这意味着,函数对象可以在函数外部被修改,从而影响函数的行为。例如:
 
 复制代码#include <iostream>using namespace std;class Foo {public:    Foo& operator++() {        ++count;        return *this;    }    int getCount() const {        return count;    }private:    int count = 0;};Foo func1(Foo& f) {    return f;}Foo& func2(Foo& f) {    return f;}int main() {    Foo f1;    func1(f1)++; // 返回函数对象本身,可以修改f1的count值    cout << f1.getCount() << endl; // 输出1    Foo f2;    func2(f2)++; // 返回指向函数对象的引用,直接修改f2的count值    cout << f2.getCount() << endl; // 输出1    return 0;}
如果函数返回函数的值,则返回的是函数计算的结果,而函数对象本身不会被修改。例如:
 
 复制代码#include <iostream>using namespace std;class Foo {public:    Foo operator+(const Foo& other) const {        Foo result;        result.count = count + other.count;        return result;    }    int getCount() const {        return count;    }private:    int count = 0;};Foo func3(Foo f1, Foo f2) {    return f1 + f2; // 返回函数的值,不会修改f1和f2的count值}int main() {    Foo f1, f2;    Foo f3 = func3(f1, f2); // 返回函数的值,不会修改f1和f2的count值    cout << f3.getCount() << endl; // 输出0    return 0;}
因此,返回函数对象本身和返回函数的值虽然在语法上相似,但在实际使用中存在着明显的区别。
 | 
 |