简体   繁体   中英

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. For example SimpleFactoryPattern should be put in the simplefactory.h file. 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. The problem is that my linter yields errors saying that it doesn't know where the SharedInterfaces namespace comes from and so on. 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. If I import, that's, include the required headers in my simplefactory.cpp file I face the redefinition error. What is the right way to handle this in C++?

You header file should only have declarations, something like this:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM