简体   繁体   English

C ++类对象函数

[英]C++ Class Object Function

I'm trying to understand how this type of function works and how you would use it. 我试图了解这种类型的功能如何工作以及如何使用它。

I assume there's some class we'll call it test. 我假设有一些课我们称之为测试。

class Test {

}

I saw this type of function in a header file and I'm trying to figure out what it does. 我在头文件中看到了这种类型的函数,我试图找出它的作用。 And how to use it properly. 以及如何正确使用它。

Test& testFunction();

Appreciate the help. 感谢帮助。

What's in front of the function name is the type that the function will return. 函数名称前面的内容是函数返回的类型。 In this case, testFunction is returning a Test object. 在这种情况下, testFunction返回一个Test对象。 The & in this case (reference) means that it will return a Test -reference. &在这种情况下(引用)意味着它将返回一个Test reference。 This is important if you wish to modify the returned object when you call the function. 如果您希望在调用函数时修改返回的对象,这一点很重要。 Or use it in some way not possible with "return-by-value". 或者以“按价值返回”无法实现的某种方式使用它。

Your code doesn't tell us much about what you're going to be doing with the return value, but here is a good example that's used quite commonly: 您的代码并没有告诉我们您将使用返回值做什么,但这是一个很常见的例子:

Test & T::f() {
    // do something

    return *this;
}

*this here is the actual object on which its method .f is being called. *this是调用其方法.f的实际对象。 What's special here is that since we are returning a reference, we can chain calls while maintaining the original object. 这里特别的是,因为我们正在返回一个引用,所以我们可以在保持原始对象的同时链接调用。 *this will be the same *this every time. *this每次都是这个*this With return-by-value we aren't able to do this. 以价值回报,我们无法做到这一点。 For example: 例如:

By reference: 引用:

Test & T::f() {

    this->x++;

    return *this;

}


int main() {

    Test t;

    t.x = 5;

    t.f().f();

    std::cout << t.x; // 7 as we expect

}

By value: 按价值:

Test T::f() { ... } // notice the omission of &

int main() {

    Test t;

    t.x = 5;

    t.f().f();

    std::cout << t.x; // 6

}

t is changed only once because the object is lost on the next call. t仅更改一次,因为对象在下一次调用时丢失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM