[問題] 請問語法哪裡有錯?

看板C_and_CPP (C/C++)作者 (if(Ithink) exist; )時間16年前 (2009/02/02 19:22), 編輯推噓3(302)
留言5則, 3人參與, 最新討論串1/1
[error message] main.cpp cannot call member function `Shape* Shape::Docreate()' without object [main.h] #include <iostream> using namespace std; class Shape { public: virtual void print() { cout << "Shape." << endl; } Shape* Docreate(); }; class test : public Shape { public: void print(){ cout << " test " << endl; } }; class Circle: public Shape { public: void print(){ cout << "Circle." << endl; } }; class Rect: public Circle { public: void print() { cout << "Rect." << endl; } }; ============================================================================= [main.cpp] #include <iostream> #include "main.h" using namespace std; Shape* Shape::Docreate() { return new test; } int main() { Rect s2; //Shape *s[2] = {new Circle(), new Rect()}; Shape *s3 = Shape::Docreate(); // error ! 不太知道小弟觀念哪裡有錯,請指教! Shape *s1 = new Circle; s1 = &s2; s3->print(); s1->print(); //s2->print(); system("pause"); return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 125.225.16.127

02/02 19:32, , 1F
static Shape* Docreate() {...}
02/02 19:32, 1F

02/02 19:56, , 2F
謝謝樓上,可以請問為何要加上static?
02/02 19:56, 2F

02/02 19:58, , 3F
是從這裡看的 Shape::Docreate()
02/02 19:58, 3F

02/03 22:23, , 4F
這樣不用宣告object 即可使用member variable/function
02/03 22:23, 4F

02/04 22:33, , 5F
樓上 我搞懂了 謝謝您~~
02/04 22:33, 5F
文章代碼(AID): #19XjTsSx (C_and_CPP)
文章代碼(AID): #19XjTsSx (C_and_CPP)