为什么我得到 不是 的成员?我试图传递一个字符串并从中返回

问题描述 投票:-1回答:3

我正在尝试将字符串传递给要排序的函数。然后从中返回排序后的字符串。它不会编译,甚至说“ binarySort不是其他成员”。

这是不允许做的事情吗?

这是课程文件

#include "Others.h"
#include <iostream>

using namespace std;

char Others::inputCheck(char guess) {
    while (!isalpha(guess)) { //If the inputs are not alphabets, keep looping.
        cout << "Enter again: ";
        cin >> guess;
    }
    cin.ignore(1, '\n');
    guess = tolower(guess);

    return guess;
}

string Others::binarySort(string sampleText) {
    //Bubble sorting the string. (Copy pasted)
    for (int i = 0; i < sampleText.length(); i++)
    {
        for (int j = i + 1; j < sampleText.length(); j++)
        {
            if (sampleText[i] > sampleText[j]) //if previous has bigger ascii value than next,
            {
                //swapping the prev and next characters
                char temp = sampleText[i];
                sampleText[i] = sampleText[j];
                sampleText[j] = temp;
            }
        }
    }
    return sampleText;
}

这是头文件。

#ifndef OTHERS_HEADER
#define OTHERS_HEADER
#pragma once
class Others
{
public:
    char inputCheck(char guess); //Function to check if inputs are alphabets.
    string binarySort(string sampleText);
};

#endif

主要功能。

#include <iostream>
#include "Others.h"

using namespace std;
int main() {
    string sortedText, sampleText = "toibeawn";
    Others sorter;
    sortedText = sorter.binarySort(sampleText);
    cout << "Text after sorted:\n";
    cout << sortedText;

    return 0;
}

The error code it produced

如果不用于函数,则排序有效。

c++ bubble-sort
3个回答
1
投票

您在声明using namespace std之前包含“ Others.h”,这将导致所包含的标题中无法识别string

在标题“ Others.h”中添加using namespace std;,错误将消失。

通常,在标头中包含using namespace std是不好的做法,最好只写std::string


0
投票

std::string binarySort(std::string sampleText)

需要名称空间


0
投票

一切都很好。需要更改是简单的更改。

  • 在标题中包括此标题:#include <iostream>并使用std名称空间。

因此更改后,标题看起来像

#ifndef OTHERS_HEADER
#define OTHERS_HEADER
#pragma once

#include <iostream>
using namespace std;

主要问题是,由于iostream标头和std名称空间的不足,在标头中字符串无法解析。

注意:请始终先尝试包含语言标题,然后再包含您的自定义标题。

© www.soinside.com 2019 - 2024. All rights reserved.