簡體   English   中英

如何使用引用聲明 function?

[英]How to declare function using reference?

我正在制作這個程序來檢查 C 類型字符串的字母和數字字符。 我正在使用 C 類型的字符串,因為它用於賦值,否則我會選擇使用std::string

function如何申報? 就我而言,我希望將strSAlphaSNum作為salphanum存儲在 function 中。 這就是我使用引用的原因,但我不明白如何聲明它而不給我一個未定義的錯誤。

我一直在尋找,但我對功能不熟悉,並且不太了解它們。 這就是我問的原因。

下面是代碼:

#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;

void seperate(char (&s)[], char (&alpha)[], char (&num)[]);

int main() {
    char str[100];
    char SAlpha[100];
    char SNum[100];

    cout << "Insert a string: ";
    cin.getline(str,100);

    strcpy(SAlpha, str);
    strcpy(SNum,str);

    cout << "Alphabetic characters " << endl;

    for (int i = 0; i < strlen(SAlpha); i++) {
        if (isalpha(SAlpha[i])) {
            cout << " " << SAlpha[i];
        }
    }
    cout << endl;
    cout << "Numeric characters " << endl;
    for (int i = 0; i < strlen(SNum);i++) {
        if (isdigit(SNum[i])) {
            cout << " " << SNum[i];
        }
    }

    seperate(str, SAlpha, SNum);    //UNDEFINED FUNCTION
    return 0;
}

您收到“未定義”錯誤,因為您只聲明了 seperate seperate() function 但尚未實現它,例如:

#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;

// THIS IS JUST A DECLARATION!!!
void seperate(char (&s)[100], char (&alpha)[100], char (&num)[100]);

int main() {
    char str[100];
    char SAlpha[100];
    char SNum[100];

    cout << "Insert a string: ";
    cin.getline(str,100);

    strcpy(SAlpha, str);
    strcpy(SNum,str);

    cout << "Alphabetic characters " << endl;

    for (int i = 0; i < strlen(SAlpha); i++) {
        if (isalpha(SAlpha[i])) {
            cout << " " << SAlpha[i];
        }
    }
    cout << endl;
    cout << "Numeric characters " << endl;
    for (int i = 0; i < strlen(SNum);i++) {
        if (isdigit(SNum[i])) {
            cout << " " << SNum[i];
        }
    }

    seperate(str, SAlpha, SNum); // <-- OK TO CALL SINCE THE FUNCTION IS DECLARED ABOVE...

    return 0;
}

// ADD THIS DEFINITION!!!
void seperate(char (&s)[100], char (&alpha)[100], char (&num)[100])
{
    // do something here...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM