首页 > 解决方案 > 无法初始化引用/表达式必须具有类型类

问题描述

我正在做一个快速的二叉树程序作为家庭作业,但我遇到了奇怪的错误,我似乎无法弄清楚如何修复。通常我用 C# 编程,而 C 只是略有不同,但足以让我感到困惑。

这是给出错误的代码:

void SortArray() {//bubble sorting by float value of 'b'
int flag = 0;

do {
    flag = 1;

    for (int i = 0; i < arraySize - 1; i++)
    {
        if (stubList[i].b > stubList[i + 1].b) {
            Swap(stubList[i], stubList[i + 1]);
            flag = 0;
        }
    }
} while (flag == 0);

printf("Sorted by value of variable 'b'"); _getch(); _getch();
}

这是整个脚本:

#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;

struct stub
{
    char crown[51];//some custom name - can be empty
    float b;//comparable value for tree sort
    int c;//limited by maxint
    stub *l;//left node(normally smaller "b" value than this node)
    stub *r;//right node(normally bigger "b" value than this node)
};

stub *stubList[255];//empty list of a stub array with a safe casual amount
int arraySize = 0;

stub *head = NULL;//main stub(first)
stub *latest = NULL;//latest stub

stub *st = NULL;//used for creating and checking

FILE *fs = NULL;
char fileName[255];

int maxint = 20;//for var 'c'

void BTreeNodeToArray(stub *s) {
    stubList[arraySize] = s;

    arraySize++;
}

void Swap(stub &s1, stub &s2) {
    stub temp = s2;

    s1 = s2;
    s2 = temp;
}

int MaxMin(int num) {
    int clampedInt = num;
    if (num < 0) clampedInt = 0;
    else if (num > maxint) clampedInt = maxint;

    return clampedInt;
}

//Create a completely new stub with crown, b, and c variables being filled here
void CreateElement() {
    st = new stub;
    printf("Adding information for node:\n");
    printf("Node name: "); gets_s(st->crown);
    printf("\n");

    float f;
    printf("Node float value (B): "); scanf_s("%f", &f);
    st->b = f;
    printf("\n");

    int d;
    printf("Node integer value (C): "); scanf_s("%d", &d);
    st->c = d;
    printf("\n");
    st->c = MaxMin(st->c);

    st->l = NULL;
    st->r = NULL;
}

//creates the very first stub(root/head)
void CreateFirst() {
    printf("First in tree. Adding root node...\n");

    CreateElement();
    head = st;
    latest = head;
    BTreeNodeToArray(head);

    printf("Added head stub\ncrown: %s\nValue: %f\nExtra: %d", head->crown, head->b, head->c);
    getchar();
    getchar();
}

void AddStub() {
    if (head == NULL) {
        CreateFirst();
    }
    else {
        CreateElement();//create newest node
        latest = st;
        st = head;
        int depth = 0;
        while (1) {
            if ((latest->b <= st->b)) {//choose left if true
                printf("Went left\n");
                depth++;
                if (st->l == NULL) {//node free, assign here
                    printf("Node assigned at depth %d\n", depth);
                    st->l = latest;
                    BTreeNodeToArray(latest);
                    getchar();
                    getchar();
                    break;
                }
                else {//loop again with next node
                    //printf("New loop (left)\n");
                    st = st->l;
                }
            }
            else {//choose right
                printf("Went right\n");
                depth++;
                if (st->r == NULL) {//node free, assign here
                    printf("Node assigned at depth %d\n", depth);
                    st->r = latest;
                    BTreeNodeToArray(latest);
                    getchar();
                    getchar();
                    break;
                }
                else {//loop again with next node
                    //printf("New loop (right)\n");
                    st = st->r;
                }
            }
        }
    }
}

void ViewArray() {
    for (int i = 0; i < arraySize; i++)
    {
        printf_s("Node [%d]:\n\tCrown: %s\n\tweight: %f\n\tExta value(0 - %d): %d\n", i, stubList[i]->crown, stubList[i]->b, maxint, stubList[i]->c);
    }
    getchar();
}

void SortArray() {//bubble sorting by float value of 'b'
    int flag = 0;

    do {
        flag = 1;

        for (int i = 0; i < arraySize - 1; i++)
        {
            if (stubList[i].b > stubList[i + 1].b) {
                Swap(stubList[i], stubList[i + 1]);
                flag = 0;
            }
        }
    } while (flag == 0);

    printf("Sorted by value of variable 'b'"); _getch(); _getch();
}

void ProcessArray() {
    char c = ' ';
    int found = 0;

    printf("Process with character: \n"); c = _getch();

    if (arraySize <= 0) {
        printf("No List!");
        return;
    }

    char chkstr[5];
    for (short i = 0; i < 5; i++)//simple assign to a 'string' 5 times
    {
        chkstr[i] = c;
    }

    for (int i = 0; i < arraySize; i++)
    {
        if (strstr(stubList[i]->crown, chkstr) != NULL) {
            // contains
            printf("B = %f at [%d] \n", stubList[i]->b, i);
            found++;
        }
    }

    if (found > 0) {
        printf("---Found: %d with character %c---", found, c);
    }
    else {
        printf("No elements found with '%c'", c);
    }
    getchar();
}

void ExportArray() {
    FILE *fs = NULL;
    char fileName[255];
    errno_t err;

    printf("Save to file as: \n"); gets_s(fileName);

    if (strlen(fileName) == 0) {
        printf("Failed to create file. File name empty!");
        _getch();
        _getch();
    }

    err = fopen_s(&fs, fileName, "wb");
    if (err != 0) {
        printf("Failed to create file!!!");
        _getch();
        _getch();
        return;
    }

    for (int i = 0; i < arraySize; i++)
    {
        int written = fwrite(&stubList[i], sizeof(stub), 1, fs);
        //fwrite(&gr[i], sizeof(student), 1, fs);
    }
    int numclosed = _fcloseall();

    printf("Exported to file: %s", fileName);
    getchar();
}

void CleanReset() {//reset all values and release memory (function used for import)
    for (int i = 0; i < arraySize; i++)
    {
        delete stubList[i];
    }

    arraySize = 0;
    st = NULL;
    head = NULL;
    latest = NULL;
}

void ImportArray() {
    FILE *fs = NULL;
    char fname[255];
    errno_t err;

    printf("Open FIle: "); gets_s(fname);

    err = fopen_s(&fs, fname, "rb");
    if (err == 0) {
        CleanReset();

        fseek(fs, 0, SEEK_END);
        long size = ftell(fs);
        arraySize = size / sizeof(stub);//get amount of students saved
        fseek(fs, 0, SEEK_SET);

        int i = 0;

        st = new stub;
        fread_s(&st, sizeof(stub), sizeof(stub), 1, fs);
        stubList[i] = st;
        while (!feof(fs)) {
            i++;
            st = new stub;
            fread_s(&st, sizeof(stub), sizeof(stub), 1, fs);
            stubList[i] = st;
        }

        printf("File data imported. Size: %d", arraySize);
        getchar();
        return;
    }

    printf("Failed to import file!!!");
    getchar();
}

void main()
{
    system("chcp 65001");//use utf8

    char izb = 'i';

    while (izb != '0') {
        system("cls");

        printf_s("1. Add stub\n");
        printf_s("2. View Array\n");
        printf_s("3. Sort Array\n");
        printf_s("4. Process\n");
        printf_s("5. Export array to file\n");
        printf_s("6. Import array from file\n");
        printf_s("0. Exit\n\n");

        printf_s("Choose action:\n"); izb = _getch();

        switch (izb)
        {
        case '1':
            AddStub();
            break;
        case '2':
            ViewArray();
            break;
        case '3':
            SortArray();
            break;
        case '4':
            ProcessArray();
            break;
        case '5':
            ExportArray();
            break;
        case '6':
            ImportArray();
            break;
        case '0':
            //Exit();
            break;
        }
    }
}

标签: c++reference

解决方案


错误是您想将 a 传递给stub *需要 a 的函数stub &。第一个是指针,第二个是引用。

你有两个选择。

第一个选项(恕我直言推荐):

更改您的交换函数以接受指针而不是引用。

void Swap(stub *s1, stub *s2) {
    stub temp = *s2;

    *s1 = *s2;
    *s2 = temp;
}

第二种选择:

在传递给交换之前取消引用参数:

Swap(*(stubList[i]), *(stubList[i + 1]));

您必须了解列表中的数据类型是指向存根的指针,函数Swap需要引用,这在 C++ 中是不同的。

为了更好地理解,我建议阅读以下内容:https ://www.geeksforgeeks.org/pointers-vs-references-cpp/


推荐阅读