为什么在这种情况下使用* this返回对象引用?

时间:2018-02-21 20:00:34

标签: c++ computer-science

我正在采取的课程说,返回此对象引用(使用* this)主要用于链接等号(例如:b = d = c = a)但是,当我超载时,我无法理解这个返回是如何工作的' ='运营商。 如果我不打算使用任何一种链条,是否还有必要?这个return语句是如何工作的?非常感谢你。

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<a data-bind="attr: { href: url, 'data-page': details }">Test link</a>

1 个答案:

答案 0 :(得分:0)

假设我们制作两个Rational进行演示。

Rational r1(1,2), r2(2,3);

r1 = r2;

当我们这样做时,首先r1将等于r2。然后操作将返回r1。就像任何函数调用一样,如果需要,我们可以选择忽略返回值。

另一方面,我们也可以选择不忽视它。

Rational r1(1,2), r2(2,3), r3;

r3 = (r1 = r2);

用于强调首先r1 = r2,即将返回r1这一事实的括号。下一个r3 = r1

这与使用函数的原理相同。

#include <iostream>

int print(int x) {
    std::cout << x << std::endl;
    return x;
}

void increase(int x) {
    std::cout << x + 5 << std::endl;
}

int main() {
    print(5); // We can ignore the return value, and just print the number

    int x = print(7); // We can print the number and store the value in a variable

    increase(print(3));  // We can print the value and pass it on to the increase function

    return 0;
}
相关问题