overloading a simple = operator

淺唱寂寞╮ 提交于 2019-12-12 03:57:32

问题


I am trying to overload part of my class to a string and I can't get the overloading to work. Alternatively, I will also have a long long overload, but I just assume that it will be the same excepted for long long instead of string.

class FileData
{
public:
    string extensions_;                 
    unsigned long long containsBytes_;      
};

string& operator = (string& s , FileData& fd)
{
    s= fd.extensions_;
    return s;
}

string extName = fileVector[0];

The error I keep getting is ERROR:'operator=' must be a member function. I also tried using istream but that also didn't work.

Anybody know how I could go about this?


回答1:


To be able to assign to a string from your class, you'll need a conversion operator:

class FileData
{
public:

    // Conversion to string
    operator string() const {return extensions_;}

    string extensions_;                 
    unsigned long long containsBytes_;      
};

You can only overload the assignment operator as a member of your class, for the purpose of assigning to an object of that class.




回答2:


You can't overload the operator= of std::string. What you probably want is a cast operator:

    class FileData
    {
    public:
        string extensions_;
        unsigned long long containsBytes_;

        operator string()
        {
            return extensions_;
        }
    }


来源:https://stackoverflow.com/questions/15867531/overloading-a-simple-operator

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