c++ - 使用基于范围的 For 循环和 Char 指针字符串

标签 c++ pointers c++11

<分区>

我是 C++11 的新手,坦率地说,我已经一年多没用过 C++,所以一开始我有点生疏。我正在根据旧的大学教科书做一些练习,在尝试迭代 char 指针字符串时遇到了问题(例如:char * c = "a string";)。我在谷歌上找不到任何有用的东西。我已经习惯了 Java,其中 foreach 循环可以遍历任何集合。我知道指针是如何工作的,但是我从 C++ 休假让我对实际使用它们的语法一无所知。谁能告诉我为什么以下代码(特别是 convert() 函数)会导致编译错误,其中“开始”和“结束”未在此范围内声明?

Ex12_01_RomanType.h

#ifndef EX12_01_ROMANTYPE_H
#define EX12_01_ROMANTYPE_H

class RomanType {
  public:
    RomanType();
    RomanType(char * n);
    virtual ~RomanType();

    char * toString();
    int getValue();
  private:
    char * numeral;
    int decimal;

    void convert();
};

#endif // EX12_01_ROMANTYPE_H

Ex12_01_RomanType.cpp

#include "Ex12_01_RomanType.h"

RomanType::RomanType() {
  // Default Constructor
  numeral = "I";
  decimal = 0;
  convert();
}

RomanType::RomanType(char * n) {
  // Specific Constructor
  numeral = n;
  decimal = 0;
  convert();
}

RomanType::~RomanType() {
  delete numeral;
}

char * RomanType::toString() {
  return numeral;
}

int RomanType::getValue() {
  return decimal;
}

void RomanType::convert() {
  /* Iterates over each character in the numeral string and adds that
     character's value to the decimal value. This method should only
     be called once during the constructor. */
  for(char c : numeral) {
    if(c == 'M') decimal += 1000;
    else if(c == 'D') decimal += 500;
    else if(c == 'C') decimal += 100;
    else if(c == 'L') decimal += 50;
    else if(c == 'X') decimal += 10;
    else if(c == 'V') decimal += 5;
    else if(c == 'I') decimal += 1;
    else decimal += 0;
  }
}

抱歉,如果这个问题对某些人来说似乎很基础。 Java 把我宠坏了。

最佳答案

Range-based-for 适用于数组、具有成员 beginend 的类,或者当有适当的非成员 开始结束

如果不遍历所有 c 风格的字符串(指向以 NUL 结尾的 char 数组的指针),您将无法找到“结尾”通过它。

最简单的修复方法就是使用 std::string,它将与基于范围的for 一起使用。

(编辑:现在想起来了,即使直接使用char数组也要小心:

const char myString[] = "Hello";
for ( auto c : myString ) //...

因为您将处理数组的所有 6 成员,包括 NUL 终止符。虽然你不能在这里这样做。)

关于c++ - 使用基于范围的 For 循环和 Char 指针字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18020517/

相关文章:

c - 当我们取消引用 FILE 指针时会发生什么?

c++ - 这段代码应该做什么? (引用右值)

c++ - 在用户输入时捕获输入流

c++ - ostream_iterator increment应该在什么情况下使用?

c++ - 无法将新对象分配给 cpp 中的指针指针类型

c++ - 自注册全局对象

c++ - 在 C++11 中弃用静态类成员

c++ - C++ 的默认赋值操作行为是什么?

c++ - C++14 中 char 类型下限的变化是否会破坏与补码系统的兼容性?

c++ - 为什么这个指针没有被分配给一个新对象?