簡體   English   中英

為什么這不能作為成員函數中的默認參數傳遞?

[英]Why this can not be passed as default parameter in member function?

我試圖將當前長度值作為默認參數作為函數參數傳遞。 但編譯器顯示錯誤

“'這個'可能不會在這種情況下使用”

任何人都可以告訴我我犯的錯誤是什么。

class A
{

    private:
    int length;
    public:
    A();
    void display(int l=this->length)
    {
        cout<<"the length is "<<l<<endl;
    }

};


int main()
{

    A a;
    a.display();    
    return 0;

}

您的會員功能:

void display(int l=this->length)

在概念上等同於:

void display(A * this, int l=this->length); //translated by the compiler

這意味着,你在表達式中使用一個參數,這是C ++中不允許的其他參數的默認參數,如§8.3.6/ 9(C ++ 03)所述,

每次調用函數時都會計算默認參數。 函數參數的評估順序未指定 因此,函數的參數不應在默認參數表達式中使用 ,即使它們未被計算。

請注意,C ++不允許這樣:

int f(int a, int b = a); //illegal : §8.3.6/9

解決方案是添加一個不帶參數的重載:

void display()
{
    display(length); //call the other one!
}

如果您不想再添加一個函數,請為參數選擇一個不可能的默認值 例如,因為它描述了永遠不會為負的長度 ,那么您可以選擇-1作為默認值,並且您可以將您的函數實現為:

void display(int l = -1)
{
      if ( l <= -1 ) 
           l = length; //use it as default value!
      //start using l 
}

您可以改為使用用戶重載和轉發。

class A
{
    private:
    int length;
    public:
    A();

    void display()
    {
        display(this->length);
    }

    void display(int l)
    {
        cout<<"the length is "<<l<<endl;
    }
};

在編譯時,沒有對象,所以沒有這個。

如果該成員函數可以訪問屬性本身,為什么要將對象的一個​​屬性作為默認值傳遞給成員函數?

暫無
暫無

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

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