我的函数调用出错了,有人能解释一下原因吗
I am getting An error on my function call, can someone explain why?
当我试图调用我的成员函数将数组复制到另一个数组时,我遇到了一个错误。我不确定我是不是说错了。我认为我在大多数部分都有正确的语法,但我也不确定成员函数是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的值,因为它已被分配,您需要释放它。
对不起,你的代码真的一团糟。
相关文章:
- 有人能解释一下为什么下界是这样工作的吗C++的
- 我是c ++的新手,你能解释一下在这种情况下的指针吗
- 你能解释一下什么运行时错误是如何解决它的吗?
- 有人能解释一下这些说法背后的逻辑是什么吗
- 谁能解释一下这个BFS代码是如何工作的?
- 谁能解释一下C++中关于cin.tie()的代码?
- 你能解释一下这个语法吗:ros::rate loop_rate(10);
- 谁能解释一下上面的代码是如何工作的以及使用哪个概念
- 有人能解释一下getline和char的问题吗
- 有人能解释一下特殊的std::函数模板参数列表语法(这个奇怪的类型(Types..))吗
- 引用变量何时合适,为什么?你能解释一下实际的语法和位置吗?
- 谁能解释一下这个简单逻辑背后的逻辑?我迷路了
- 有人能解释一下最多一次不变和存在、所有权和守恒规则是什么吗?
- 谁能解释一下递归结束后这些语句是如何执行的
- 有人能解释一下这个功能是如何工作的吗
- 你能解释一下这个C++函数定义的语法吗?
- 你能解释一下如何调用类的方法吗?
- 有人能解释一下C++/C#的魔力吗
- 有人能解释一下他们的意思是list.pushback文档(不会使迭代器无效)吗
- 有人能解释一下这行代码的作用吗?它是关于链表的