为什么我会收到此错误:
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 。
关于c++ - 为什么 C++ 将赋值 (=) 视为重载运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20560299/