簡體   English   中英

如果 C++ 構造函數不返回任何內容,如何在表達式中使用它?

[英]How can the C++ constructor be used in expressions if it does not return anything?

#include <bits/stdc++.h>
using namespace std;
class vec{
public:
    int x;
    int y;
    vec(int a, int b)
    {
        x = a; y = b;
    }
    vec operator+(vec that)
    {
        vec ans(0, 0);
        ans.x = this->x + that.x;
        ans.y = this->y + that.y;
        return ans;
    }
};
int main()
{
    vec a(0, 1);
    a = a + vec(2, 3); // how does this line work
    printf("%d %d\n", a.x, a.y);
    return 0;
}

每個人都說構造函數不返回任何東西。 看起來它正在返回一個對象。 我嘗試尋找臨時或未命名的對象,但找不到任何特定於此類表達式的內容。

構造函數“返回”他們正在建模的類的一個實例,所以當你這樣做時

x = Foo(0,0);

x 被賦值為構造函數返回的新對象 Foo

所以當你做

vec a(0, 1);
a = a + vec(2, 3); // how does this line work
printf("%d %d\n", a.x, a.y)

是“等效”的

vec a(0, 1);
b = vec(2,3);
a = a + b;
printf("%d %d\n", a.x, a.y)

構造函數是一個特殊的函數,它在內存中初始化對象。 對象可能在堆棧或堆上。 調用構造函數將初始化內存。 請注意,構造函數是 C++ 語法糖。

vec x(0, 1);                 // creates the object named x of type vec on the stack
vec *px = new vec(2, 3);     // creates the object pointed by px on the heap

x = x + vec(2, 3);           // vec(2, 3) creates a temporary object on stack 
                             // and initializes it with the parameters. 
                             // The overloaded operator+ on the object x is called, 
                             // passing the temporary object as the formal parameter
                             // 'that' of operator+ and it returns a temporary object
                             // on the stack that is copied back into the variable x
                             // as a result of the = assignment operation

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM