這是我Pizaa.h類是不能夠找到另一個類(獨立的頭文件):C++
#pragma once
#ifndef PIZZA_H
#define PIZZA
#include <iostream>
#include <string>
#include <list>
#include <limits>
#include <vector>
#include <cstdlib>
using namespace std;
/****************************
Abstract Base Pizza Class
*****************************/
class Pizza{
string name;
string dough;
string sauce;
std::list<string> topping;
public:
Pizza(string name,string dough,string sauce);
void prepare();
virtual void bake()=0;
virtual void cut()=0;
void box();
string getName();
void addTopping(string str);
void getTopping(std::list<string>& lst);
virtual ~Pizza();
};
#endif
這是cheesePizza.h
#pragma once
#ifndef CHEEZEPIZZA_H
#define CHEEZEPIZZA_H
#include <iostream>
#include <string>
#include <list>
#include <limits>
#include <vector>
#include <cstdlib>
#include "Pizza.h"
using namespace std;
class cheesePizza:public Pizza{
public:
cheesePizza();
~cheesePizza();
virtual void bake();
virtual void cut();
};
#endif
這是veggiePizza.h
#pragma once
#ifndef VEGGIEPIZZA_H
#define VEGGIEPIZZA_H
#include <iostream>
#include <string>
#include <list>
#include <limits>
#include <vector>
#include <cstdlib>
#include "Pizza.h"
class veggiePizza:public Pizza{
public:
veggiePizza();
~veggiePizza();
virtual void bake();
virtual void cut();
};
#endif
這是我的工廠類:
#include <iostream>
#include <string>
#include "Pizza.h"
#include "cheesePizza.h"
#include "veggiePizza.h"
using namespace std;
class SimplePizzaFactory{
public:
enum PizzaType {
cheesePizza,
veggiePizza
};
Pizza* createPizza(PizzaType type)
{
switch(type){
case cheesePizza:
// Pizza* p = new cheesePizza(); ##Here
//delete(p); ##Here
case veggiePizza:;
// return new veggiePizza();
}
throw "Invalid Pizza Type";
}
};
int main()
{
Pizza* p = new cheesePizza();
delete(p);
return 0;
}
我SimplePizzaFactory
方法createPizza()
是無法找到new cheesePizza()
& new veggiePizza()
,我得到以下錯誤,如果我取消#Here
$ g++ -Wall -c SimplePizzaFactory.cpp -o SimplePizzaFactory.o
SimplePizzaFactory.cpp: In member function ‘Pizza* SimplePizzaFactory::createPizza(SimplePizzaFactory::PizzaType)’:
SimplePizzaFactory.cpp:19:33: error: expected type-specifier before ‘cheesePizza’
Pizza* p = new cheesePizza();
^
SimplePizzaFactory.cpp:21:8: error: jump to case label [-fpermissive]
case veggiePizza:;
^
SimplePizzaFactory.cpp:19:25: error: crosses initialization of ‘Pizza* p’
Pizza* p = new cheesePizza();
^
SimplePizzaFactory.cpp:17:8: warning: enumeration value ‘veggiePizza’ not handled in switch [-Wswitch]
switch(type){
我的所有文件即*.o
& *.cpp
都放在同一個文件夾。
我無法弄清楚爲什麼會出現這個錯誤。相同的代碼 Pizza* p = new cheesePizza(); delete(p);
裏面main()
工作正常,但如果您取消註釋#Here
它給編譯錯誤。
你有一個枚舉'cheesePizza'和一個'cheesePizza'類。 –
你是對的'改變枚舉PizzaType {奶酪,蔬菜};'解決了這個問題 –
我不明白多態是如何應用於此,它應該只是一個普通的類與屬性來填充(當然不是字符串,我想看到你填滿了象鼻和奶酪比薩訂單)。 – Blindy