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

标签 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)

测试.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;
}

测试.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 .

参见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]时,然后 struct A 的 10 个对象在堆上动态创建并调用它们的构造函数。

如果你此时不想“构造”10个对象,那么我建议你使用 std::vector<A> .

您只需 push_back( object_of_type_A )创建 vector 时将其添加到 vector 。

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

关于c++ - 为什么 C++ 将赋值 (=) 视为重载运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20560299/

相关文章:

c++ - 共享指针的循环依赖

c++ - 使用字符串文字和不同字符列表初始化数组声明时有什么区别?

java - 不使用局部变量时无法推断Comparator的类型参数

c++ - "No match for operator="试图在 C++ 中遍历映射

c - Visual Studio 命令提示符 C/C++ 编译错误 "Error Code C2143: syntax error : missing ' )' before ' ;' "

linux - 将循环索引的值(增量)分配给bash中的变量

c++ - 当我构建隐藏窗口(在后台运行)时,如何在 'opencv' 函数中使用获取像素颜色?

c++ - CImg 编译器错误

c++ - 有没有办法在 C++ 中将方法存储在某种类型的 vector 中?

c - Webrtc2sip : error adding symbols: DSO missing from command line