Operatrator [] as non-static function

ε祈祈猫儿з 提交于 2020-01-07 04:42:04

问题


Code:

SchedulingItem operator[](Schedule obj,int el){
    return obj.OfVector().at(el);
}

Error:

academia::SchedulingItem academia::operator[](academia::Schedule, int)' must be a nonstatic member function
     SchedulingItem operator[](Schedule obj,int el)

Where is the problem?


回答1:


The problem is that, just as the message says, this function must be a non-static member function.

That's simply a law of C++, for operator[].

You've instead made it a non-member, or "free" function.




回答2:


operator[] must be a non-static member of your Schedule class, eg:

class Schedule
{
private:
    std::vector<SchedulingItem> m_vec;
public:
    SchedulingItem& operator[](int el);
};

SchedulingItem& Schedule::operator[](int el)
{
    return m_vec.at(el);
}


来源:https://stackoverflow.com/questions/44010316/operatrator-as-non-static-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!