看板 C_and_CPP 關於我們 聯絡資訊
[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
chrisdar:static Shape* Docreate() {...} 02/02 19:32
hikaru06:謝謝樓上,可以請問為何要加上static? 02/02 19:56
chrisdar:是從這裡看的 Shape::Docreate() 02/02 19:58
Dreamer77:這樣不用宣告object 即可使用member variable/function 02/03 22:23
hikaru06:樓上 我搞懂了 謝謝您~~ 02/04 22:33