2012-05-26 55 views
0

我有一個重載的巨大問題[]我完全按照示例中所示使用它,它不起作用甚至沒有被編譯器看到。重載[]運算符和複製構造函數不起作用

我得到的錯誤:

no match for 'operator<<' in 'std::cout << * moj

的第二個問題是,即使我使用拷貝構造,如果我刪除原來的對象複製一個自敗。但是現在當我添加析構函數時就崩潰了。

C:\Documents and Settings\Duke\Moje dokumenty\MaciekK\String\main.cpp|90|error: no match for 'operator<<' in 'std::cout << * moj'| 
#include <iostream> 
#include <cstdio> 
#include <stdio.h> 
#include <cstring> 
using namespace std; 

class String{ 
public: 
char* napis; 
int dlugosc; 

    char & operator[](int el) {return napis[el];} 
    const char & operator[](int el) const {return napis[el];} 
    String(char* napis){ 
    this->napis = napis; 
    this->dlugosc = this->length(); 
} 

String(const String& obiekt){ 

    int wrt = obiekt.dlugosc*sizeof(char); 
    //cout<<"before memcpy"<<endl; 
    memcpy(this->napis,obiekt.napis,wrt); 

    //cout<<"after memcpy"<<endl; 
    this->dlugosc = wrt/sizeof(char); 
} 

~String(){ 
    delete[] this->napis; 
} 

int length(){ 
    int i = 0; 
    while(napis[i] != '\0'){ 
     i++; 
    } 
    return i; 
} 


void show(){ 
    cout<<napis<<" dlugosc = "<<dlugosc<<endl; 
} 



}; 




int main() 
{ 

String* moj = new String("Ala ma kota"); 
// cout<< moj[0] <<endl; // I GETT ERROR NO MATH FOR OPERATO<< IN STD:: COUTN<< * MOJ 
String* moj2 = new String(*moj); 

moj->show(); 
delete moj; 
moj2->show(); 
return 0; 
} 
+2

請你可以編輯你的問題,包括**確切的**錯誤信息。 –

+0

這就是我可以粘貼的; /。 – Yoda

回答

1

的問題是,mojString *,而不是一個String。因此moj[0]不會調用您的operator <<,它只是取消引用指針。

+0

cout <<&moj [0] << endl; 這將打印一個地址 我應該如何糾正超載? – Yoda

1

您的問題是:

調用上沒有內存分配函數返回的任何地址解除功能是未定義行爲。 代碼中存在未定義的行爲,因爲您從未使用new []分配內存,但在析構函數中調用delete []delete[] this->napis;)。

您沒有正確執行構造函數&的拷貝構造函數。
您需要在構造函數中以及在複製構造函數中分配動態內存。目前,您不會在構造函數中分配內存,並且在複製構造函數中執行淺拷貝而不是深拷貝。

你應該有:

String(char* napis) 
{ 
    //I put 20 as size just for demonstration, You should use appropriate size here. 
    this->napis = new char[20]; <-------------- This is Important! 
    memcpy(this->napis,napis,12); 
    this->dlugosc = this->length(); 
} 

String(const String& obiekt) 
{ 

    int wrt = obiekt.dlugosc*sizeof(char); 
    this->napis = new char[wrt]; <-------------- This is Important! 
    memcpy(this->napis,obiekt.napis,wrt); 
    this->dlugosc = wrt/sizeof(char); 
}  

另外,你需要調用deletemoj2,以避免在節目的最後一個內存泄漏。

delete moj2; 

Here是你的程序的在線版本與上面說的修改和它工作得很好。

+0

真棒!我忘了完全忘了我需要這樣做! 但那個重載操作符呢。如果我在這裏取消第63行http://wklej.org/id/760541/ 我得到這個: 63 |錯誤:'std :: cout << *(moj2 + 16u )「| 但我想得到napis的第三個字母。 – Yoda

相關問題