我的函数调用出现错误,有人可以解释原因吗?

时间:2016-10-30 20:58:39

标签: c++ arrays class

当我尝试调用我的成员函数将数组复制到另一个数组时,出现错误。我不确定我是在说错了什么。我认为我在大多数部分都有正确的语法,但我也不确定成员函数是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;
}

} 

2 个答案:

答案 0 :(得分:0)

CopiedArray = Sort.CopyArray(Array);

但是这个函数被定义为void

void CopyArray::CopyArray(int * Array)

您无法设置指向void函数结果的指针。

当然,您没有在Sort的情况下声明,而CopyArray并非像@Bim所提到的那样staic

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

对不起,你的代码真的很乱。

答案 1 :(得分:0)

在您的示例中,您正在访问成员函数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.