我可以使用以下代码通过“结构”返回两个数组;但不能将代码翻译成“类”。还附有“类”代码和错误。
请点亮它。我必须在我的项目中使用“类”和多个数组。
1) 用“结构”
struct strA{
int *p;
int *p1;
};
strA setValue(int n)
{
strA strB;
strB.p=new int[n];
strB.p1=new int[n];
for (int i=0; i<n;i++)
{
strB.p[i]=i;
strB.p1[i]=i*2;
}
return strB;
}
int main(){
const int N=3;
strA strC;
strC=setValue (5);
for (int i=0; i<N;i++)
{
cout<< strC.p[i]<<endl;
cout<< strC.p1[i]<<endl;
}
return 0;
}
与“类(Class)”。结果是“错误 C3867:‘strA::setValue’:函数调用缺少参数列表;使用‘&strA::setValue’创建指向成员的指针”
class strA{ public: int *p; int *p1; public: strA(); ~strA(){delete p, delete p1;} strA setValue(int n); }; strA strA::setValue(int n) { strA strB; strB.p=new int[n]; strB.p1=new int[n]; for(int i=0; i<n;i++) { strB.p[i]=i; strB.p1[i]=i*2; } return strB; } int main(){ const int N=3; strA strC; strC.setValue (N); for (int i=0; i<N;i++) { cout<< strC.setValue<<endl; cout<< strC.p1[i]<<endl; } return 0; }
最佳答案
我将首先解决您提到的错误。此代码还存在其他问题。
错误是因为main中的这一行:
cout<< strC.setValue<<endl;
setValue
是一个函数,必须使用如下参数调用它:
strC.setValue(N);
其他问题:
- 您不能使用
cout
打印从setValue
返回的对象 除非你重载了<<
类运算符strA
. - 在
setValue
你定义了一个对象的函数strB
然后将内存分配给它的成员。此内存未释放。您正在释放的是对象的成员strC
在main
中定义.查看strA
的析构函数你会明白的。
main
在代码的第一个(“struct”)版本中可以在第二个(“class”)版本中使用,因为 p
和 p1
是公开的。
关于c++ - 可以在结构中返回两个数组,但不能在 C++ 类中返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52219185/