简体   繁体   中英

Is it possible to pass a class member variable to a function as default variable?

I want to pass class variable a in a class function as default parameter. I can do this by using #define but I want to do it by using the class member. Is there any way to do this?

#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;
    }

This program shows error: invalid use of non-static data member

One simple solution is to use overloading instead:

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
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM