簡體   English   中英

為什么C ++將賦值(=)視為重載運算符?

[英]Why is C++ treating assignment (=) as overloaded operator?

為什么會出現此錯誤:

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;
};
a_list [ i ] = foo2 ();

foo2()返回指向A的指針,但是a_list[i]是類型A的對象。

另外,最好使用new分配動態內存而不是malloc

請參見C ++中的“ new”和“ malloc”以及“ calloc”有什么區別?

代替:

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

你可以有:

a_list = new A[10];

為了釋放內存,請使用

delete [] a_list; 

更好的選擇是使用std::vector<A> 在這種情況下,您不必管理內存分配,您可以自己取消分配,因為這些是自動完成的。

編輯2:

當您調用new A[10] ,將在堆上動態創建struct A 10個對象,並調用它們的構造函數。

如果您此時不想“構造” 10個對象,則建議您使用std::vector<A>

您可以在創建矢量時將push_back( object_of_type_A )到矢量上。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM