overloading a simple = operator

2019-08-30 03:13发布

问题:

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