为什么C ++将赋值(=)视为重载运算符?

时间:2013-12-13 06:18:17

标签: c++ compiler-errors

为什么我会收到此错误:

test.cpp:11:28: error: no match for ‘operator=’ in ‘*(((Test*)this)->Test::a_list + ((unsigned int)(((unsigned int)i) * 20u))) = Test::foo2()’

编译以下代码时(通过g++ test.cpp -o test

TEST.CPP:

#include "test.h"

Test::Test () {}

void Test::foo1 ()
{
   int i;
   a_list = ( A* ) malloc ( 10 * sizeof ( A ) ); 

   for ( i = 0; i < 10; i++ )
      a_list [ i ] = foo2 ();
   }
}

A* Test::foo2 ()
{
   A *a;

   a = ( A* ) malloc ( sizeof ( A ) ); 

   return a;
}

Test.h:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

typedef struct
{
   double x;
   double y;
   string z;
} A;

class Test
{
   public:
      Test ();
      void foo1 ();
   private:
      A* foo2 ();
      A *a_list;
};

1 个答案:

答案 0 :(得分:3)

a_list [ i ] = foo2 ();

foo2()返回指向A的指针,但a_list[i]A类型的对象。

此外,如果您使用new来分配动态内存而不是malloc,那会更好。

请参阅What is the difference between "new" and "malloc" and "calloc" in C++?

而不是:

a_list = ( A* ) malloc ( 10 * sizeof ( A ) ); 

你可以:

a_list = new A[10];

要解除分配内存,请使用

delete [] a_list; 

更好的选择是使用std::vector<A>。在这种情况下,您不必自行管理内存分配和解除分配,因为这些是自动完成的。

编辑2:

当你调用new A[10]时,会在堆上动态创建10个struct A对象,并调用它们的构造函数。

如果你不想构建&#39;此时有10个对象,我建议您使用std::vector<A>

创建它时,您可以push_back( object_of_type_A )向量。

http://en.cppreference.com/w/cpp/container/vector

相关问题