2013-12-13 94 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