簡體   English   中英

我如何從函數中返回無法更改的值?

[英]How can i return from a function a value that just can't be changed?

我知道一個函數可以返回const引用,但是還有其他方法可以實現這種行為嗎? 意思是,我想返回一個無法修改的值。

#include <string>
#include <iostream>    
using namespace std;  

class A {  
public:  
    A( int x, int y): _x(x), _y(y) {};  
    int _x;  
    int _y;  
};  

const A genObjA()
{
    return A( 0,0 );
}

int main(int argc, char **argv) {

    A new_obj = genObjA();
    std::cout << new_obj._x;
    new_obj._x = 10; // user can change new_obj
    std::cout << new_obj._x;

}

這將打印

0
10

您不必返回const引用,可以返回const對象。

const Object function_name() {
// ...
}

您不修改返回值,而是修改它的副本。 在此代碼中,您無法執行genObjA()._x=10;

為了實現您的目標,您可以編寫額外的類:

class A_const{
protected:
    int _x;  
    int _y;
    operator=(const A_base&)=default;
public: 
    A()=default;
    A(const A_base&)=default;
    A( int x, int y): _x(x), _y(y) {};
    int x(){return _x;}
    int y(){return _y;}
    //or
    int get_x(){return _x;}
    int get_y(){return _y;}
};

class A {  
public:
    using A_const::A_const;
    A(const A&)=default;
    int& x(){return _x;}
    int& y(){return _y;}
    //or
    int& set_x(int val){return _x=val;}
    int& set_y(int val){return _y=val;}
};

const A_const genObjA_const(){
    return A_const(0, 0);
}

如果您想要一個簡單的修改保護措施,則可以使用PIMPL習慣用法。

但是,如果您對與您的班級一起工作的同事的理智有合理的信念,請使用const引用。 如果你想確保,說明為什么你不希望對象被修改,從而使你的同伴可以按照你的想法(並得出了相同的結論)的原因。 PIMPL習慣用法試圖將您從確定的傻瓜中解救出來。 但是堅定的傻瓜甚至可以解決PIMPL,因此在嘗試中弄亂代碼毫無意義。

暫無
暫無

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

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