返回类型不匹配(或不匹配)

Return type mismatch (or not)

本文关键字:不匹配 返回类型      更新时间:2023-10-16

我对这段代码有点困惑。这实际上是我的,但我仍然不明白为什么这个编译没有任何警告。

#include <iostream>
class Line {
    private:
        int length;
    public:
        Line(void);
        Line(int);
        int getLength(void);
        Line& operator = (const Line&);
};
Line::Line(int a) : length(a) {}
int Line::getLength(void) { return length; }
Line& Line::operator = (const Line& line)           // The function return type is reference of a value of the Line type.
{
    length = line.length;
    return *this;                                   // The function actually returns dereferenced (*this) value.
}
int main(void)
{
    Line line {2};
    Line line_a {0};
    line_a = line;
    std::cout << line_a.getLength() << std::endl;
    return 0;
}

唯一的区别是没有&号。它仍然会编译

#include <iostream>
class Line {
    private:
        int length;
    public:
        Line(void);
        Line(int);
        int getLength(void);
        Line operator = (const Line&);
};
Line::Line(int a) : length(a) {}
int Line::getLength(void) { return length; }
Line Line::operator = (const Line& line)            // The function return type is reference of a value of the Line type.
{
    length = line.length;
    return *this;                                   // The function actually returns dereferenced (*this) value.
}
int main(void)
{
    Line line {2};
    Line line_a {0};
    line_a = line;
    std::cout << line_a.getLength() << std::endl;
    return 0;
}

this是指向当前对象的指针。解引用this就得到了那个对象。当函数的返回类型是引用而您返回一个对象时,将返回对该对象的引用。所以,你正在返回一个对你从解引用this指针得到的对象的引用。没有任何警告的理由。

如果你没有解引用this指针,那么你会得到一个编译错误,因为你会试图返回(引用)一个指针,这将与函数的返回类型冲突。

让我们考虑这段代码:

#include <iostream>
int global_variable = 8;
int function(void)
{
    return global_variable;
}
int main(void)
{
    function() = 16;        // Compiling this code would give error: lvalue required as left operand of assignment.
    std::cout <<  global_variable << std::endl;
    return 0;
}

但是,如果我们稍微修改一下这段代码,将函数返回类型更改为引用int -这将把lvalue更改为rvalue (int somenumberlvalue, int& somenumberrvalue)。

#include <iostream>
int global_variable = 8;
int& function(void)
{
    return global_variable;
}
int main(void)
{
    function() = 16;
    std::cout <<  global_variable << std::endl;      // The global_variable becomes 16! (it was 8);
    return 0;
}
相关文章: