2013-12-13 61 views
2

为什么我得到这个错误:为什么C++将赋值(=)视为重载运算符?

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

使用了'malloc'分配包含'的std :: string',这不是一个简单的结构类型 - 其构造不会被调用。 – milleniumbug

+0

你用C++编写C代码而不是编写C++代码的任何原因? – greatwolf

+0

别人的代码(omxplayer) – puk

回答

3
a_list [ i ] = foo2(); 

foo2()指针返回到A,但​​是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)的载体,你创建它。

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

+0

我可以只交换'new' for'malloc' = P你能演示一个小脚本来为我做这个吗? – puk

+0

@puk看到我的更新。 –

+0

我不知道'new'与结构的工作以及 – puk