【发布时间】:2015-07-18 09:46:56
【问题描述】:
我正在尝试实施策略设计模式作为练习。我的课程非常简单:
1) Fly.cpp
class Fly
{
public:
Fly();
bool fly();
};
class CanFly : public Fly
{
public:
bool fly()
{
return true;
}
};
class CantFly : public Fly
{
public:
bool fly()
{
return false;
}
};
2) Animal.cpp
class Fly;
class Animal
{
Fly myFly;
public:
Animal(Fly f);
void setFly(Fly f);
Fly getFly();
};
Animal::Animal(Fly f)
{
myFly = f;
}
void Animal::setFly(Fly f)
{
myFly = f;
}
Fly Animal::getFly()
{
return myFly;
}
3) Dog.cpp
#include <iostream>
using namespace std;
class Animal;
class Dog : public Animal
{
public:
Dog(Fly f);
};
Dog::Dog(Fly f)
{
setFly(f);
cout << "Dog : " << getFly().fly() << endl;
}
4) Bird.cpp
#include <iostream>
using namespace std;
class Animal;
class Bird : public Animal
{
public:
Bird(Fly f);
};
Bird::Bird(Fly f)
{
setFly(f);
cout << "Bird : " << getFly().fly() << endl;
}
5) AnimalTest.cpp
#include <iostream>
using namespace std;
class Dog;
class Bird;
class CanFly;
class CantFly;
int main()
{
Fly f1 = new CanFly();
Fly f2 = new CantFly();
Bird b(f1);
Dog d(f2);
return 0;
}
我在构建代码时遇到的错误是:
Animal.cpp:5:6: error: field 'myFly' has incomplete type 'Fly'
Fly myFly;
^
谁能帮我解释一下为什么?
谢谢
【问题讨论】:
-
你知道什么是抽象类吗?
-
应该不能不“不能”。阅读关键字
virtual -
fly构造函数需要一个主体 -
... 阅读参考资料和
const给你一些事情做:-) -
请阅读基本的编程介绍。
标签: c++ inheritance design-patterns