是否可以将类成员变量作为默认变量传递给函数?

Md.*_*ash 3 c++

我想在类函数中传递类变量 a 作为默认参数。我可以通过使用 #define 来做到这一点,但我想通过使用类成员来做到这一点。有没有办法做到这一点?

#include <iostream>
    
    class Test
    {
    private:
        int a=5;
    public:
        Test(){}
        void function(int value=a){ //i want to use class variable a here.
            std::cout<<value<<std::endl;
        }
        ~Test(){}
    };
    
    int main()
    {
        Test var1;
        var1.function();
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

该程序显示错误:无效使用非静态数据成员

Som*_*ude 13

一种简单的解决方案是改用重载:

class Test
{
private:
    int a=5;
public:
    void function(int value){
        std::cout<<value<<std::endl;
    }

    // Overload for no arguments, use a as "default" argument
    void function(){
        function(a);  // Call using the member variable
    }
};
Run Code Online (Sandbox Code Playgroud)