2011-11-30 344 views
2

有沒有人知道我在做什麼錯誤,並向我解釋爲什麼它不讓我聲明任何東西爲圓形? 主要錯誤:無法將變量'c'聲明爲抽象類型'circle'

int main(void){ 
... 
    circle c; 
... 
} 

circle.h

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

class circle : public shape { 

    double diameter, circum, radius; 

public: 

    virtual void draw(){ 
     cout<< "Circle"<< endl; 
    } 
}; 

shape.h

#include <string> 
#include <iostream> 

using namespace std; 

class shape{ 

public: 
    virtual void draw() const = 0; 
}; 
+3

你忘了'const' –

回答

8
virtual void draw() const { 
    cout<< "Circle"<< endl; 
} 

您應該添加const關鍵字像上面的例子。

4

你的shape類中的繪圖函數被聲明爲const,而你的circle類中的繪圖函數不是。因此,圈內的人不會覆蓋形狀。所以它仍然是抽象的,因爲它沒有重載純虛函數。

2

你在循環繪製的定義後缺少一個const。

virtual void draw() const { cout<<"Circle"<<endl; } 

當使用抽象函數,其函數原型/簽名具有相匹配-exactly-

編輯:Blegh,通過30秒毆打。

-1

如果你懶得看你編譯器的輸出像這樣的顯示:

g++ main.cpp 
main.cpp: In function ‘int main()’: 
main.cpp:5:12: error: cannot declare variable ‘c’ to be of abstract type ‘circle’ 
circle.h:6:29: note: because the following virtual functions are pure within ‘circle’: 
shape.h:9:18: note:  virtual void shape::draw() const