C ++ string comparison

class Song {

public:
    const string getAutherName();
}

void mtm::RadioManager::addSong(const Song& song,const Song& song1) {

    if (song.getAutherName() == song1.getAutherName())

}

      

I am getting this error:

Invalid arguments ' Candidates are: std::basic_string<char,std::char_traits<char>,std::allocator<char>> getAutherName() ' - passing 'const mtm::Song' as 'this' argument of 'std::string mtm::Song::getAutherName()' discards qualifiers [- fpermissive]

      

Why is it used basic_string

and not string

! How to fix it?

+3


source to share


4 answers


Your getAutherName()

function is not const

, so it cannot be called via const Song&

. Modify the function declaration as follows:



class Song {

public:
    const string getAutherName() const;
}

      

+5


source


You are calling getAutherName()

on const Songs

, so you need to make this method const

:

const string getAutherName() const;

      



It is not clear why you are returning const string

. Either return a string

, or return a const reference by one:

const string& getAutherName() const;
string getAutherName() const;

      

+2


source


std::string

is a typedef for basic_string<char, std::char_traits<char>, std::allocator<char> >

, the compiler just expands the typedef in the error message.

However, why the code doesn't work I don't know. You seem to have cut out the part of the error message where the "."

+1


source


You need to add qualification const

in getAutherName

to allow it to be called on const objects Song

:

//| -- Returns a `const` `string` (this is bad practice
//v    because it inhibits optimization)
const string getAutherName() const;
// Can be called on a `const`    ^
// `Song`. This is good practice |
// because it it allows `getAutherName()`
// to be used in more places, and it encourages
// const-correctness.

      

0


source







All Articles