2016-06-26 48 views
-1

我不明白爲什麼這並不編譯:我可以在C重寫一個字符串返回類型函數++

#include<iostream> 
#include<string> 

using namespace std; 


class Product { 

public: 
    virtual void print() = 0; 
    virtual void slog() = 0; 
    virtual void loft() = 0; 
}; 

class Bike: public Product { 

private: 
    string s; 

public: 

    Bike(string x){ 
    s = x; 
    } 

    void print() { 
    std::cout << "Bike"; 
    } 

    int slog() { 
    return 4; 
    } 

    string loft() { 
    return s; 
    } 
}; 

int main() { 
    string s("Hello"); 
    Product *p = new Bike(s); 
    p->print(); //works fine 
    cout << p->slog();//works fine  
    cout << p->loft(); //error 
    return 0; 
} 
  1. 錯誤上面的代碼的結果。爲什麼我不能重寫字符串類。
  2. 我想使用指針p調用loft()
  3. 有沒有辦法實現這個使用指針對象的抽象類Product
+1

你不_override_'的std :: string'。請修復你的代碼。請顯示您的代碼中包含的逐字錯誤。 –

+0

請下一次,讓你的代碼更具可讀性。從長遠來看,它會變得更順暢:) –

+0

我會開始看'行30:7:錯誤:虛擬函數'slog'具有與它重寫的函數不同的返回類型('int')返回類型爲'void') int slog(){...'並且自己處理來自頂部的錯誤(通常更有意義,修復第一個錯誤,然後重新運行,因爲「後續錯誤」如果有什麼不可修復的,只需複製上面問題中的剩餘錯誤,看看人們是否可以進一步幫助。謝謝。 – Dilettant

回答

3

首先,你需要包含字符串#include <string>

+0

感謝回覆@izzak_pyzaak 。但s在Bike構造函數中實例化。即使你說什麼。問題不在於s。編譯器說的是預期的int返回類型代替字符串。 –

+1

你有沒有加過'#include ' –

+0

是的I添加字符串標題。編譯器說你不能返回任何返回類型,除了int或void在函數覆蓋。 –

1

loft方法沒有問題,您有一個print方法的問題。子類返回類型爲string,而基類返回類型爲void,因此您並不是真正覆蓋該函數。編譯器會在基類中看到void print()的聲明,並且您不能對此執行cout。 這裏是你的代碼,幾乎沒有修復和評論,它應該工作正常。

#include <iostream> 
#include <string> 
using namespace std; 

class Product { 
public:   
    virtual void print() = 0; 
    virtual int slog() = 0; 
    virtual string loft() = 0; 
    //added virtual destructor so you can use pointer to base class for child classes correctly 
    virtual ~Product() {}; 
}; 

class Bike: public Product { 
    string s; 
public: 
    Bike(string x) { 
     s = x; 
    } 
    void print() { 
     cout << "Bike"; 
    } 
    int slog() { 
     return 4; 
    } 
    string loft() { 
     return s; 
    } 
}; 

int main() { 
    string s("Hello"); 
    Product *p = new Bike(s); 
    p->print(); 
    cout << p->slog(); 
    cout << p->loft(); 
    return 0; 
} 

另外,請嘗試你的代碼更好的下一次格式化,它可以更容易閱讀

+0

感謝您回覆@ buld0zzr 打印函數返回類型是無效的只能看到我已經更新了以前的代碼。實際上,我們不能返回任何返回類型的函數覆蓋,除了void和int –

+0

@HrudwikChowdary現在您的代碼編譯和運行對我來說很好,只需將虛擬析構函數添加到父類 – buld0zzr

+0

@buldOzzr感謝此工作正常 –

相關問題