可以在struct中返回两个数组,但不能在类C ++中返回

时间:2018-09-07 09:10:04

标签: c++ visual-c++

我可以用下面的代码通过'struct'返回两个数组;但无法将代码转换为“类”。还附带了“类”代码和错误。

请在上面照亮。我必须在项目中使用“类”和多数组。

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;
        }
    

2 个答案:

答案 0 :(得分:2)

我将首先解决您提到的错误。此代码还有其他问题。

错误是由于main中的这一行:

cout<< strC.setValue<<endl;

setValue是一个函数,必须使用类似这样的参数来调用它:

strC.setValue(N);

其他问题:

  1. 您不能使用cout打印从setValue返回的对象 除非您为类<<重载了strA运算符。
  2. setValue函数中,您定义了一个对象strB,并为其成员分配了内存。此内存不会释放。您要释放的是strC中定义的对象main的成员。看看strA的析构函数,您将了解。

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

答案 1 :(得分:1)

首先,作为P.W.的答案您将在此行遇到编译错误 cout<< strC.setValue<<endl;,因为您忘记传递函数setValue(int n)的参数。

第二,将setValue(int n)函数写成您所写的是不合适的。我建议您编写如下函数:

void ::setValue(int n)
{
  this->p=new int[n];
  this->p1=new int[n];  
  for (int i=0; i<n;i++)
  {
    this->p[i]=i;
    this->p1[i]=i*2;
  }
}

我认为您是新手,您应该阅读有关面向对象编程的更多信息。