我的函数调用出错了,有人能解释一下原因吗

I am getting An error on my function call, can someone explain why?

本文关键字:一下 能解释 出错 函数调用 错了 我的      更新时间:2023-10-16

当我试图调用我的成员函数将数组复制到另一个数组时,我遇到了一个错误。我不确定我是不是说错了。我认为我在大多数部分都有正确的语法,但我也不确定成员函数是void还是int是否重要。

Main.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Class.h"
using namespace std;
int main()
{
// Max size of array
int MaxRange = 1000;
// Get System time
unsigned seed = time(0);
// seed random number generator
srand(seed);
// allocate memory for array
int * Array = new int[1000];
int * CopiedArray = new int[1000];
// Randomly generate numbers into array
for (int i = 0; i < 1000; i++)
{
    Array[i] = 1 + rand() % MaxRange;
}
//print array
for (int j = 0; j < 1000; j++)
{   
    cout << Array[j] << endl;
}   
CopiedArray = Sort.CopyArray(Array);

return 0;
}
Class.h
#include <iostream>
using namespace std;

class Sort
{
public:
void CopyArray(int * Array);

};
Class.cpp
#include <iostream>
#include "Class.h"
using namespace std;
void CopyArray::CopyArray(int * Array)
{
// Allocate memory for copied array
int * CopiedArray = new int[1000]
//copy date to array
for(int i = 0; i < 1000; i++)
{ 
    CopiedArray[i] = Array[i]
}
cout << " THIS IS THE COPIED ARRAY" << endl;
// print copied array 
for (int j = 0; i < 1000; i++)
{
    cout << CopiedArray[j] << endl;
}
} 

在您的示例中,如果访问成员函数CopyArray而没有对象,则无法执行此操作。您必须创建一个Sort类的对象,然后使用它来访问成员。否则使CopyArray为静态,然后将其更改为

class Sort
{
    public:
        static int* CopyArray(int* Array); // to access this function just use the name of class and `::` 
   //   int* CopyArray(int* Array); // to access this function you must have an object of Sort class
};
int* Sort::CopyArray(int * Array)
{
    int * CopiedArray = new int[1000]; // semicolon missin
    // your code processing here
    return CopiedArray;
}

int main()
{
    CopiedArray = Sort::CopyArray(Array); // accessing the static member function `CopyArray`
//   or you can create an object of Sort class but you must also make Copyarray non-static to be able to:
//  Sort theSort;
//  CopiedArray = theSort.CopyArray(Array);
    return 0;
}

*同样在您的示例中,您将为指向int:的指针分配一个void

    CopiedArray = Sort.CopyArray(Array);// because in your example CopyArray returns void.
CopiedArray = Sort.CopyArray(Array);

然而,该函数被定义为无效

void CopyArray::CopyArray(int * Array)

不能将指针设置为void函数的结果。

当然,您并没有在Sort的实例中声明,并且CopyArray不是像@Bim提到的staic

您也不应该更改CopiedArray的值,因为它已被分配,您需要释放它。

对不起,你的代码真的一团糟。