我最近从JAVA切换到C ++。我正在尝试实现工厂设计模式。
这是我的文件。
Shape.h
#pragma once
class Ishape
{
public:
virtual void draw()=0;
};
Rectangle.h
#pragma once
#include"Shape.h"
class Rectangle :public Ishape
{
public:
void draw();
};
Rectangle.cpp
#include"Rectangle.h"
#include<iostream>
void draw()
{
std::cout << "Rectangle Draw" << std::endl;
}
Square.h
#pragma once
#include"Shape.h"
class Square :public Ishape
{
public:
void draw();
};
Square.cpp
#include"Square.h"
#include<iostream>
void draw()
{
std::cout << "Square Draw" << std::endl;
}
ShapeFactory.h
#pragma once
#include "Shape.h"
#include<iostream>
class ShapeFactory
{
public:
static Ishape* getShape(std::string type);
};
ShapeFactory.cpp
#include"ShapeFactory.h"
#include"Rectangle.h"
#include"Square.h"
static Ishape* getShape(std::string type)
{
Ishape* s = nullptr;
if (type == "Rectangle")
{
s= new Rectangle;
}
else if (type == "Square")
{
s= new Square;
}
return s;
}
客户代码:
Source.cpp
#include<iostream>
#include"ShapeFactory.h"
int main()
{
using namespace std;
Ishape* shape = ShapeFactory::getShape("Rectangle");
shape->draw();
return 0;
}
当我运行它时,我得到以下运行时错误:
Severity Code Description Project File Line Suppression State
Error LNK2005 "void __cdecl draw(void)" (?draw@@YAXXZ) already defined in Rectangle.obj 1
Error LNK2019 unresolved external symbol "public: static class Ishape * __cdecl ShapeFactory::getShape(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?getShape@ShapeFactory@@SAPAVIshape@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function _main Project1 C:\Users\nikhil\source\repos\Project1\Project1\Source.obj 1
Error LNK1120 1 unresolved externals Project1 C:\Users\nikhil\source\repos\Project1\Debug\Project1.exe 1
几点:我读到保留单独的头文件和代码文件是一个好习惯,这就是我遵循的原因。
我按照工厂设计模式的例子。(https://www.tutorialspoint.com/design_pattern/factory_pattern.htm)
任何人都可以建议,如何克服错误。从c ++点的任何其他提示也将有所帮助。
Rectangle.cpp
#include"Rectangle.h"
#include<iostream>
void Rectangle::draw()
// ^^^^^^^^^^^
{
std::cout << "Rectangle Draw" << std::endl;
}
Square.cpp
#include"Square.h"
#include<iostream>
void Square::draw()
// ^^^^^^^^
{
std::cout << "Square Draw" << std::endl;
}
ShapeFactory.cpp
#include"ShapeFactory.h"
#include"Rectangle.h"
#include"Square.h"
static Ishape* getShape(std::string type)
{
Ishape* s = nullptr;
if (type == "Rectangle")
{
s= new Rectangle;
}
else if (type == "Square")
{
s= new Square;
}
return s;
}
你在OOP方面做得很好。但显然你不理解c ++的共同原则。当您在Rectangle.cpp中编写void draw()
时,您的定义实际上是自由函数,但没有Rectangle
的成员方法(在其他情况下类似)