简体   繁体   English

比较c ++字符串

[英]comparing c++ string

class Song {

public:
    const string getAutherName();
}

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

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

}

I get 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 using basic_string and not string ! 为什么使用basic_string而不是string how to fix this? 怎么解决这个问题?

Your getAutherName() function is not const , so it cannot be called through a const Song& . 你的getAutherName()函数不是const ,所以它不能通过const Song&调用。 Change the function declaration like this: 像这样更改函数声明:

class Song {

public:
    const string getAutherName() const;
}

You are calling getAutherName() on const Songs so you need to make that method const : 你在const Songs上调用getAutherName() ,所以你需要使该方法成为const

const string getAutherName() const;

It isn't clear why you return a const string . 目前尚不清楚为什么返回一个const string Either return a string , or return a const reference to one: 要么返回一个string ,要么将一个const引用返回给一个:

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

std::string is a typedef for basic_string<char, std::char_traits<char>, std::allocator<char> > , the compiler is just expanding the typedef in the error message. std::stringbasic_string<char, std::char_traits<char>, std::allocator<char> >的typedef,编译器只是在错误消息中扩展typedef。

However, why the code is not working I don't know. 但是,为什么代码不工作我不知道。 You appear to have cut out part of your error message where the ' is. 您似乎已删除了部分错误消息,其中'是。

You need to add a const qualification to getAutherName to allow it to be called on const Song objects: 您需要为getAutherName添加const限定条件,以允许在const 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM