[英]What does this passage from cppreference.com (Default arguments) mean?
從默認 arguments上的 cppreference 頁面:
非靜態 class 成員在默認 arguments 中是不允許的(即使它們沒有被評估),除非用於形成指向成員的指針或在成員訪問表達式中:
int b; class X { int a; int mem1(int i = a); // error: non-static member cannot be used int mem2(int i = b); // OK: lookup finds X::b, the static member static int b; };
我無法理解“除非用於形成指向成員的指針或在成員訪問表達式中”。 並且示例沒有給出相關代碼。
第一部分意味着您可以形成一個指向成員的指針,指向其中一個非靜態成員,例如:
class X
{
int a, b;
int mem1(int X::* i = &X::a);
//...
};
指向成員的指針是語言中相當晦澀的部分。 您可能已經看到成員 function 指針,但是您也可以像上面那樣形成指向數據成員的此類成員指針。
成員指針不是指class當前實例的成員,而是需要結合.*
或->*
運算符給出實例的對應成員,例如:
int X::mem1(int X::* i = &X::a) {
// same as `return a;` if called with default argument
// but if called with `mem1(&X::b)` same as `return b;`
return this->*i;
}
第二部分可能只是意味着可以通過通常的成員訪問表達式(使用.
或->
)引用 class 的另一個實例的成員。 該異常不允許引用當前實例的成員,因為默認參數中也不允許this
做:
class X
{
int a;
static X x;
int mem1(int i = x.a); // ok, `.` is member access
int mem2(int i = this->a); // not ok because of `this`, but `->` is member access
};
形成一個指向成員的指針:
int mem3(int X::*pointer_to_member = &X::a);
在成員訪問表達式中使用:
X global;
int mem4(int i = global.a);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.