Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/164.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 陷入字符串类的实现中_C++ - Fatal编程技术网

C++ 陷入字符串类的实现中

C++ 陷入字符串类的实现中,c++,C++,我的目标是创建一个方法,返回基于零的第i个元素,就像调用它的字符串数组一样。如果请求的位置超出字符串的范围,此方法应打印错误消息并返回空字符\0 char String::element(int i) const { if (i < m_str1) { cout << s[i]; // also the s here is undefined } else { cout << "Error"

我的目标是创建一个方法,返回基于零的第i个元素,就像调用它的字符串数组一样。如果请求的位置超出字符串的范围,此方法应打印错误消息并返回空字符\0

char String::element(int i) const
{
    if (i < m_str1) 
    {
        cout << s[i]; // also the s here is undefined
    }
    else 
    {
        cout << "Error" << endl;
    }
    return (0);
}

因此,我只想知道这是否正确,或者我是否需要添加更多,以及如何修复未定义的变量?

为了使其正常工作,您需要将s更改为指向字符数组的成员变量。您没有提供String的类定义,因此很难说该成员变量的名称

你也应该改变

char String::element(int i) const
要么

char String::element(size_t i) const

这是因为不应使用负索引值访问字符数组。如果不将i更改为无符号值,则需要确保它等于或大于零,这无论如何都不应该被允许。Toy还应该将m_str1更改为size_t或unsigned int,如果它已经更改为size_t或unsigned int,因为字符串的长度永远不应该为负

应用这些建议将使字符串和元素看起来像以下内容

class String
{
    unsigned int m_str1; // length of character string
    char* m_str; // pointer to the character string
public:
    char String::element(unsigned int i) const;
};

char String::element(unsigned int i) const
{
    if (i < m_str1) 
    {
        return m_str[i]; // Changed s to m_str
    }

    cout << "Error" << endl;
    return 0;
}

那么问题是什么呢?传统上,该参数的类型应该是std::size\u t。这里到底是什么?即使将char String::elementint i const更改为char String::elementunsigned int i const,仍然会将i标记为错误。您会得到什么样的错误?在你的问题中,s是未定义的,但我没有产生错误,那么我怎么还能给你一个错误呢?好吧,s最初有一个未定义的错误,变量没有定义,但在我改变s'以返回m_str1[i];然后我有一个错误,表达式必须有指向对象类型的指针。很抱歉,m_str1应该是m_str,我编辑了我的答案以反映这一点。我再次编辑了我的答案,使它更清楚一点。
class String
{
    unsigned int m_str1; // length of character string
    char* m_str; // pointer to the character string
public:
    char String::element(unsigned int i) const;
};

char String::element(unsigned int i) const
{
    if (i < m_str1) 
    {
        return m_str[i]; // Changed s to m_str
    }

    cout << "Error" << endl;
    return 0;
}