簡體   English   中英

c++ 從 function 返回 object

[英]c++ returning object from a function

下面的代碼顯示了一個代表復數的 class。 我的興趣是了解operator+ function。 據我了解,應該在 function operator+的框架上分配Complex res 將此 object 返回給調用者是否正確? 到此 function 返回時,幀將被彈出,但調用者將繼續使用res 除非有比看起來更多的東西,比如實際的return res可能實際上是將 object 從當前幀復制到調用者的幀。 另一種可能是operator+ function 內的代碼可能內聯在 main 的調用站點上? 根據我對語言的有限理解,在 class 中聲明的函數默認內聯在調用站點上。 任何幫助將不勝感激。

#include<iostream>
using namespace std;

class Complex {
private:
    int real, imag;
public:
    Complex(int r = 0, int i =0) {real = r; imag = i;}
    
    Complex operator+(Complex const &obj) {
        Complex res;
        res.real = real + obj.real;
        res.imag = imag + obj.imag;
        return res;
    }
    void print() { cout << real << " + i" << imag << endl; }
};

int main()
{
    Complex c1(10, 5), c2(2, 4);
    Complex c3 = c1 + c2; 
    c3.print();
}

閱讀以下評論和答案后,添加以下部分以澄清解決方案

我用以下內容更新了上面的代碼:

#include<iostream>
using namespace std;

class Complex {
private:
    int real, imag;
public:
    Complex(int r = 0, int i =0) {real = r; imag = i;}
    
    Complex operator+(Complex const &obj) {
        Complex res;
        res.real = real + obj.real;
        res.imag = imag + obj.imag;
        cout << "Address inside the function " << &res << "\n";
        return res;
    }
    void print() { cout << real << " + i" << imag << endl; }
};

int main()
{
    Complex c1(10, 5), c2(2, 4);
    Complex c3 = c1 + c2; 
    cout << "Address outside the function " << &c3 << "\n";
    c3.print();
}

output 在堆棧的兩個不同區域顯示兩個不同的地址,指示返回期間按值復制

Address inside the function 0x7fffbc955610
Address outside the function 0x7fffbc955650

將此 object 返回給調用者是否正確?

C++ 支持按引用返回和按值返回。 由於您沒有使用按引用返回,因此您沒有將 object 的引用返回給調用者。 您正在使用按值返回,因此您將對象的返回給調用者。 考慮:

int foo()
{
    int i = 2;
    return i;
}

這將返回值 2。它不返回 object i returni本身不再存在並不重要,因為它的值已經用於確定返回的值。

帶值傳輸始終使用堆棧。 當你想返回一個值時,根據調用者代碼,復制構造函數或賦值運算符可能會隱式調用並將返回值賦值給左邊的object。 (左值)

Complex  nwobj=cmpx1 + cmplx2; //copy constructor used to assign return object to lvalue

cmplx3=cmplx1+xmplx2;//operator= used to make a right assignment. 

筆記:

根據使用的編譯器及其設置,第一行中的復制構造可能會發生或可能會被省略。 可以在以下位置找到關於此的全面解釋:
SO:什么是復制省略和返回值優化?

暫無
暫無

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

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