c++ - 可以在结构中返回两个数组,但不能在 C++ 类中返回

标签 c++ visual-c++

我可以使用以下代码通过“结构”返回两个数组;但不能将代码翻译成“类”。还附有“类”代码和错误。

请点亮它。我必须在我的项目中使用“类”和多个数组。

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;
   }
  1. 与“类(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);

其他问题:

  1. 您不能使用 cout打印从 setValue 返回的对象 除非你重载了 <<类运算符 strA .
  2. setValue你定义了一个对象的函数strB然后将内存分配给它的成员。此内存未释放。您正在释放的是对象的成员 strCmain 中定义.查看 strA 的析构函数你会明白的。

main在代码的第一个(“struct”)版本中可以在第二个(“class”)版本中使用,因为 pp1是公开的。

关于c++ - 可以在结构中返回两个数组,但不能在 C++ 类中返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52219185/

相关文章:

c# - 如何正确地将 char * 从非托管 DLL 返回到 C#?

c++ - 将结构序列化/反序列化为二进制数据包

c++ - 模板化二维数组错误

C++ 简单华氏转换

c++ - 由于计算开销,应该避免多次调用 std::find 还是可以接受这种情况?

c++ - 使用 DWORD 解决重载函数调用

c++ - 为什么在堆上迭代一个大数组比在堆栈上迭代相同大小的数组更快?

c++ - GDI 动画 C++ 无法正常工作

visual-c++ - 如何在 VC++ 中的另一个测试项目中使用来自一个测试项目的类?

c++ - 在 MFC 按钮的文本上方制作图标