我无法使用类变量作为同一类函数的默认参数

I am unable to use a class variable as a default argument for the same class's function

本文关键字:类函数 参数 默认 类变量      更新时间:2023-10-16

我很清楚第7行是无效的。但是我想使用类变量作为方法(apple)的默认参数。

class trial{
public:
int i=10 ;
    void apple(int i=this.i){
       cout<<i<<endl;
    }
    void display(){
         cout<<i<<endl;
    }
};

Replace

void apple(int i=this.i){
     cout<<i<<endl;
}

白马王子;

void apple(int i){
     cout<<i<<endl;
}
void apple(){
     apple(i);
}

不能访问函数的正式参数列表中的成员变量

你不能这样设置默认值。如果你想用相同的名称显示对象的变量而不是函数的参数,使用:

void apple(int i){
     // class member
     cout << this.i << endl;
     // function variable
     cout << i << endl;
}