![](/img/trans.png)
[英]default argument : invalid use of 'this' outside of a non-static member function
[英]Using a non static value as default argument in a function
有沒有一種很好的方法可以將非靜態值作為函數中的默認參數? 我已經看到了對同一個問題的一些較舊的回答,這些回答總是最終明確寫出過載。 這在C ++ 17中仍然是必要的嗎?
我想做的是做類似的事情
class C {
const int N; //Initialized in constructor
void foo(int x = this->N){
//do something
}
}
而不是必須寫
class C {
const int N; //Initialized in constructor
void foo(){
foo(N);
}
void foo(int x){
//do something
}
}
這使得過載的目的不那么明顯。
一種相對優雅的方式(在我看來)是使用std::optional
來接受參數,如果沒有提供參數,則使用對象的默認值:
class C {
const int N_; // Initialized in constructor
public:
C(int x) :N_(x) {}
void foo(std::optional<int> x = std::nullopt) {
std::cout << x.value_or(N_) << std::endl;
}
};
int main() {
C c(7);
c.foo();
c.foo(0);
}
您可以在標准的第11.3.6節中找到有效/無效的完整說明。 第9小節描述了成員訪問(摘錄):
非靜態成員不應出現在默認參數中,除非它顯示為類成員訪問表達式(8.5.1.5)的id-expression,或者除非它用於形成指向成員的指針(8.5.2.1)。[示例:以下示例中的X :: mem1()聲明格式錯誤,因為沒有為用作初始化程序的非靜態memberX :: a提供對象。
int b;
class X {
int a;
int mem1(int i = a);// error: non-static memberaused as default argument
int mem2(int i = b);// OK; useX::b
static int b;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.