【问题标题】:Dereferencing vs Indexing on const string reference [duplicate]在 const 字符串引用上取消引用与索引 [重复]
【发布时间】:2016-06-20 06:52:56
【问题描述】:

对于下面这段代码中的 const string 引用变量 str

效果很好:for(int i=0; str[i]; i++)

抛出错误:for(int i=0; *(str+i); i++)

错误:错误:'operator+' 不匹配(操作数类型为 'const string {aka const std::basic_string}' 和 'int')

// Return true if str is binary, else false
bool isBinary(const string &str)
{
   for(int i=0; *(str+i); i++){
       if(str[i]!='0' && str[i]!='1')
           return false;
   }
   return true;
}

P.S.:我可以理解这可能是一个幼稚的问题,但我也很乐意被重定向到有用的来源!

【问题讨论】:

  • std::stringchar* 不同。
  • @πάνταῥεῖ 我错了,感谢您的帮助
  • 获取char指针调用string::c_str()
  • @FedeWar 也不知道这个;我会试试这个
  • 试试the book guide and list。 (在C++ info page 找到。)

标签: c++ pointers


【解决方案1】:

str的类型是std::string,不是char*,也没有为它定义operator+(int),你可以用length成员函数获取它的大小:

bool isBinary(const string &str)
{
   for(int i=0; i < str.length(); i++){
       if(str[i]!='0' && str[i]!='1')
           return false;
    }
    return true;
}

另一方面,如果你有一个 c 字符串,你可以做第二种形式,因为 c 字符串只是以空字符结尾的字符数组。

bool isBinary(const char *str)
{
   for(int i=0; *(str+i); i++){
       if(str[i]!='0' && str[i]!='1')
           return false;
    }
    return true;
}

另外,您可以从 c++ 的 std::string 及其 c_str() 成员函数中获取 c 字符串。

const char *s = str.c_str();

【讨论】:

  • 知道了!确实,问得太天真了,谢谢!
  • 你也可以提到,你可以使用std::string::c_strstd::string获取底层const char*
  • @Zereges 已更新,谢谢。
猜你喜欢
  • 1970-01-01
  • 2022-08-19
  • 2011-06-08
  • 1970-01-01
  • 2019-06-10
  • 2014-11-25
  • 1970-01-01
  • 2016-12-02
  • 1970-01-01
相关资源
最近更新 更多