簡體   English   中英

使用此在構造函數中設置變量

[英]Setting variables in Constructor using this

所以我對Java沒問題,但對C ++還是陌生的。 我基本上是在嘗試為C ++構造一個帶有參數的構造函數,並使用this將該值分配給該對象的字段。 所以這是在Java中的樣子:

//Foo fields
    private int num;

//Foo Constructor
    public Foo(int num){
    this.num = num;
    }

我如何使用this來設置C ++中的變量? 還是這不是一個選擇? 謝謝!!

C ++有一種更干凈的方法,稱為構造函數初始化器 您可以使用以下語法來代替分配大量任務:

public MyClass::MyClass(int num): someVar(num), someOtherVar(0) {
    // constructor here
}

如果您確實要使用this ,請記住在C ++中this是一個指針,因此您必須使用指針解引用運算符,因此

this->num = num;

要么

(*this).num = num;

使用this->num ,就像在c ++中那樣是一個指針,要通過指針訪問struct / class成員,您必須使用->而不是. 在變量和成員名稱之間,這來自手冊

expression  can be read as
*x          pointed by x
&x          address of x
x.y         member y of object x
x->y        member y of object pointed by x

暫無
暫無

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

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