[英]The “this declaration has no storage class or type specifier” error in c++
I've decided to implement some design patterns in C++ just as an exercise and created a certain project architecture, the thing is that I want my patterns to live inside the patterns
directory and in different files. 我决定以练习的形式在C ++中实现一些设计模式,并创建了某种项目体系结构,但事实是我希望我的模式驻留在patterns
目录和不同文件中。 For example SimpleFactoryPattern
should be put in the simplefactory.h
file. 例如SimpleFactoryPattern
应放在simplefactory.h
文件。 The code looks like this: 代码如下:
class SimpleAutoFactory {
public:
SimpleAutoFactory() {};
~SimpleAutoFactory() {};
SharedInterfaces::IAuto *getAutoModel(EModel model) {
switch (model) {
case EModel::EFiat:
return new SharedModels::Fiat;
case EModel::ELamborghini:
return new SharedModels::Lamborghini;
case EModel::EMaserati:
return new SharedModels::Maserati;
default: throw CommonExceptions::unknownModelException;
}
}
};
Then I simply include this piece in the main.cpp and run make && make run
to compile and execute the whole thing. 然后,我将这部分内容简单地包含在main.cpp中,然后运行make && make run
来编译并执行整个过程。 The problem is that my linter yields errors saying that it doesn't know where the SharedInterfaces
namespace comes from and so on. 问题是我的linter产生错误,表明它不知道SharedInterfaces
命名空间来自何处,等等。 I suspect there must be something wrong with the structure of the project. 我怀疑项目的结构一定存在问题。 I'm sort of new to C++ but as far as I know we only declare things in headers and execute stuff in cpps. 我是C ++的新手,但据我所知,我们仅在标头中声明内容,并在cpps中执行内容。 If I import, that's, include the required headers in my simplefactory.cpp
file I face the redefinition error. 如果导入,那就是在我的simplefactory.cpp
文件中包含必需的标头,我simplefactory.cpp
遇到重定义错误。 What is the right way to handle this in C++? 用C ++处理此问题的正确方法是什么?
You header file should only have declarations, something like this: 您的头文件应该只包含声明,如下所示:
simplefactory.h: simplefactory.h:
#pragma once
// here you should also include the header files where your other classes (IAuto, Fiat etc) are declared
class SimpleAutoFactory {
public:
SharedInterfaces::IAuto *getAutoModel(EModel model); // only declaration, no definition
};
Then, in your cpp files you define your functions: 然后,在cpp文件中定义函数:
simplefactory.cpp: simplefactory.cpp:
#include "simplefactory.h"
SharedInterfaces::IAuto *SimpleAutoFactory::getAutoModel(EModel model) {
switch (model) {
case EModel::EFiat:
return new SharedModels::Fiat;
case EModel::ELamborghini:
return new SharedModels::Lamborghini;
case EModel::EMaserati:
return new SharedModels::Maserati;
default: throw CommonExceptions::unknownModelException;
}
}
Then you can either compile these files together with your main, or compile these files as a static or shared library and pass it to the linker. 然后,您可以将这些文件与主文件一起编译,也可以将这些文件编译为静态或共享库,然后将其传递给链接器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.