简体   繁体   中英

C++ Error while passing enum as default parameter by reference in C++

Here's what I'm trying to accomplish:

class Schedule
{
    public:
    enum day{MON, TUE, WED, THU, FRI, SAT, SUN};
    void isWeekend(day &dayOfWeek=SUN);
}

I'm trying to retrieve the day in the function that calls isWeekend , defaulting it to 'SUN'. On VS2017, this is the error that I see:

initial value of reference to non-const must be an lvalue.

What am I missing? The same function compiles without the & ie

void isWeekend(day dayOfWeek=SUN)

The problem is that you are declaring the parameter to be a non-const lvalue reference (as the error message suggests). An lvalue is essentially something that can be assigned to, so an lvalue reference is a reference to an existing object. SUN here, thus, is not an lvalue and therefore cannot be used to initialize the lvalue reference. A caller would have to call this method with an existing variable as its parameter if you declare it to be an lvalue reference. So remove the reference, since it's not necessary here if this is just supposed to be an input parameter.

See here for more information: http://en.cppreference.com/w/cpp/language/value_category

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