2017-04-17 37 views
0

我想实现C++单Xcode项目里面,但我得到这个错误“类的定义”:的Xcode:辛格尔顿执行错误:

Redefinition of class 

这里是我的代码(.HPP文件) :

#ifndef DoingSomething_hpp 
#define DoingSomething_hpp 
#include <stdio.h> 
#endif /* DoingSomething_hpp */ 

class DoingSomething { 

public: 
    static DoingSomething *instance(); 
}; 

这是我的.cpp文件:

#include "DoingSomething.hpp" 
class DoingSomething 
{ 
    static DoingSomething *shareInstance; 
public: 
    int doSomething() 
    { 
     /* 
     */ 
     return 6; 
    } 

    static DoingSomething *instance() 
    { 
     if (!shareInstance) 
      shareInstance = new DoingSomething; 
     return shareInstance; 
    } 
}; 

在此行中(在我的cpp文件)

class DoingSomething 

我得到这个错误:

“DoingSomething” 的重新定义。

enter image description here

任何的你知道我做错了什么或如何解决这个问题? 我会非常感谢你的帮助。

+0

.cpp文件中的整个'class'声明不属于那里。只有*实现*去那里。错误是不言自明的。您已经在标题中定义了“DoingSomething”的外观。在C++中没有做过任何事情。 – WhozCraig

回答

1

您正在同一个翻译单元DoingSomething.cpp中宣布您的班级两次,即一次在您包含的头文件中,并且再次在cpp-文件本身中。 放入头文件中的类声明,并在.cpp -file实现:

头,即DoingSomething.hpp

#ifndef DoingSomething_hpp 
#define DoingSomething_hpp 
#include <stdio.h> 

class DoingSomething { 

public: 
    int doSomething(); 
    static DoingSomething *instance(); 
}; 

#endif /* DoingSomething_hpp */ 

执行,即DoingSomething.cpp

#include "DoingSomething.hpp" 

int DoingSomething ::doSomething() { 
    return 6; 
} 

DoingSomething *DoingSomething::instance() { 
    if (!shareInstance) 
     shareInstance = new DoingSomething; 
    return shareInstance; 
}