[英]C++ Assign value of class member from a different function
假設我有一個 class:
class Test
{
public:
int x = 1;
};
並在 main 我創建一個 object 的 class 並調用一個 function 稱為 setInt:
int main()
{
Test example;
setInt(example);
std::cout << example;
}
void setInt(Test example)
{
(// random if statement)
example.x = 5;
}
這將是 output 1。
這怎么可能? 我知道在上面的示例中,變量“example”僅對 function 是本地的,但是有沒有辦法在 main() 中更改變量的值?
(請原諒代碼中的任何錯誤)
您只是復制 integer 然后分配一個新值,但不使用原始值進行操作。 如果你可以寫:
void setInt(Test& example)
{
// Now you are changing the original value here
example.x = 5;
}
然后它就可以工作了。 有一個引用運算符的替代方案,稱為指針。 它們的工作方式類似於 function 的參考。 當您在取消引用的任何地方更改它們的值時,主值也會更改。
默認情況下,將參數傳遞給 function 按值傳遞它,這會復制參數。 function 中對此副本的更改不會反映在main
中。
如果要修改傳入的參數,可以使用引用。 將您的簽名更改為:
void setInt(Test &example) { // changing example changes the argument used in main
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.