简体   繁体   中英

initializing default parameter with class member function/variable

class C {
private:
     int n{ 5 };

public:
    int return5() { return 5; }
    void f(int d = return5()) {

    }

    void ff(int d = n) {

    }


};

Why I can't initialize the functions default parameters with member class? I get an error: a nonstatic member reference must be relative to a specific object.

I think the problem because no object has been instantiated yet, but is there any approach to do it?

The default argument is considered to be provided from the caller side context. It just doesn't know the object on which the non-static member function return5 could be called on.

You can make return5 a static member function, which doesn't require an object to be called on. Eg

class C {
    ...
    static int return5() { return 5; }
    void f(int d = return5()) {
    }
    ...
};

Or make another overload function as

class C {
private:
     int n{ 5 };
public:
    int return5() { return 5; }
    void f(int d) {
    }
    void f() {
        f(return5());
    }
    void ff(int d) {
    }
    void ff() {
        ff(n);
    }
};

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