|
各位LinuxSir的大侠们,您们好,小弟实做如下代码时遇到了问题:
- #include <iostream>
- #include <string>
- using namespace std;
- class Fruit
- {
- public:
- Fruit(string name):m_sName(name){}
- virtual void eat(){}
- protected:
- string m_sName;
- };
- class Apple: public Fruit
- {
- public:
- void eat(){cout << m_sName << "削皮吃" << endl;}
- };
- class Banana: public Fruit
- {
- public:
- void eat(){cout << m_sName << "剥皮吃" << endl;}
- };
- int main(void)
- {
- Fruit *pFruit;
-
- pFruit = new Apple("红苹果");
- pFruit->eat();
- pFruit = new Banana("进口香蕉");
- pFruit->eat();
- pFruit = NULL;
- return 1;
- }
复制代码
在Debian下g++(3.3.5)编译,error如下:
- 1.cpp:15: error: base `Fruit' with only non-default constructor in class without a constructor
- 1.cpp:21: error: base `Fruit' with only non-default constructor in class without a constructor
- 1.cpp: In function `int main()':
- 1.cpp:30: error: no matching function for call to `Apple::Apple(const char[7])'
- 1.cpp:15: error: candidates are: Apple::Apple(const Apple&)
- 1.cpp:33: error: no matching function for call to `Banana::Banana(const char[9])'
- 1.cpp:21: error: candidates are: Banana::Banana(const Banana&)
复制代码
小弟的疑问是:在Fruit中已经有了构造函数,而Apple和Banana是其派生类,也需要吗?还有该pFruit做转化类型时为何要求匹配的Apple&或Banana&?
还请各位老大指点下该如何修改及为什么,谢谢了^_^ |
|