2017-04-17 51 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; 
}