【问题标题】:Xcode:Singleton implementation error: " Redefinition of class"Xcode:单例实现错误:“类的重新定义”
【发布时间】:2017-04-17 22:23:08
【问题描述】:

我正在尝试在 Xcode 项目中实现 C++ 单例,但出现此错误:

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”。

你们中的任何人都知道我做错了什么或者如何解决这个错误? 非常感谢您的帮助。

【问题讨论】:

  • .cpp 文件中的整个class 声明不属于那里。只有 实现 去那里。该错误是不言自明的。您已经在标题中定义了 DoingSomething 的外观。 C++ 中没有重做。

标签: c++ ios xcode compiler-errors


【解决方案1】:

您在同一个翻译单元DoingSomething.cpp 中声明了您的课程两次,即一次在您包含的头文件中,另一次在cpp 文件本身中。 将类声明放在头文件中,实现放在.cpp-文件中:

标头,即 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    • 1970-01-01
    相关资源
    最近更新 更多