Is it possible to add a member to string?

  c++

The one annoyance I have with the std::string class is that the only ways (that I could figure out after reading cplusplus.com’s info about it) to get the location of the last character in the string is (stringVariable.length() - 1) or stringVariable.rfind(stringVariable.back()). It’d be nice if I could just do stringVariable.last(). This is for a function I wrote in a personal project that needs to reference this number of a user’s input string.

Some ideas I had were creating a struct that is just a string and has the last() function as a member function, or a class that copies the string class and adds that member. With a struct, I’m not sure how (or if it’s possible) to make it so I can make the variable assigned to the type automatically reference the string in it so that I don’t need to make a constant member call. I’m taking the second C++ class in school right now, but we haven’t touched on C++ classes yet.

I tried reading some guides and answers here about classes, and they don’t look all that different from structs, but the more complex stuff in either case was Greek to me. I only learned how to use a struct as a holder for multiple variable types; like the name string and id int for a person, or something like that. I learned from the guides I can put functions in them, and define operator behavior too, but when I tried to define operator behavior for the string struct I made, I couldn’t get it to work.

Based on the example I read, I tried:

str &operator=(const str &ing)
{
    s = ing.s;
    return s;
}

But when I tried to test it by using = to copy a str variable to a string variable I could cout, it errors that str can’t be converted to string, so I tried a few adjustments, and after getting errors about the & and such, I ended up with:

string operator=(str ing)
{
    return ing.s;
}

Which gets the same error. Here’s the full struct test program I’m using:

#include <iostream>
#include <string>
using namespace std;

struct str
{
    string s;

    string operator=(str ing)
    {
        return ing.s;
    }

    int last()
    {
        return s.length() - 1;
    }
};

int main()
{
    str ing {"Hello World!"};
    string i = ing;
    cout << i;

    return 0;
}

If I could get the = assignment to work, I’d try to get << and such to work with str, too.

If that doesn’t turn out to be possible, my fallback is just using a function like:

int last(string str)
{
    return str.length() - 1;
}

Source: Windows Questions C++

LEAVE A COMMENT