使用.h文件中定义的C ++类

时间:2014-08-09 22:21:28

标签: c++ xcode class

我在.h文件中实现了一个类。我试图将.h文件导入到我的main.cpp中,然后在那里创建和使用该类的对象。但是,我从Xcode的乳胶版本中得到了这个错误:

ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

这是我的代码:

class.h:

using namespace std;

class Cents
{
private:
    int m_nCents;

public:
    Cents(int nCents) { m_nCents = nCents; }

    // Add Cents + Cents
    friend Cents operator+(const Cents &c1, const Cents &c2);

    int GetCents() { return m_nCents; }
};

// note: this function is not a member function!
Cents operator+(const Cents &c1, const Cents &c2)
{
    // use the Cents constructor and operator+(int, int)
    return Cents(c1.m_nCents + c2.m_nCents);
}

这是我的main.cpp:

    Cents cCents1(6);
    Cents cCents2(8);
    Cents cCentsSum = cCents1 + cCents2;
    cout << "I have " << cCentsSum .GetCents() << " cents." << endl;

    return 0;

帮助?

编辑:这是整个错误消息。

duplicate symbol __ZplRK5CentsS1_ in:
    /Users/chasemccoy/Library/Developer/Xcode/DerivedData/Testing_C++-coximuwgddopngcjrkbjugfliqkv/Build/Intermediates/Testing C++.build/Debug/Testing C++.build/Objects-normal/x86_64/operatorOverload.o
    /Users/chasemccoy/Library/Developer/Xcode/DerivedData/Testing_C++-coximuwgddopngcjrkbjugfliqkv/Build/Intermediates/Testing C++.build/Debug/Testing C++.build/Objects-normal/x86_64/main.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

3 个答案:

答案 0 :(得分:2)

尝试使用预处理程序指令隔离标头,并且永远不要在标头中定义实现:

#ifndef CENTS_HPP
#define CENTS_HPP

using namespace std;

class Cents
{
private:
    int m_nCents;

public:
    Cents(int nCents) { m_nCents = nCents; }

    // Add Cents + Cents
    friend Cents operator+(const Cents &c1, const Cents &c2);

    int GetCents() { return m_nCents; }
};

// note: this function is not a member function!
Cents operator+(const Cents &c1, const Cents &c2);

/ *在cpp或内联中执行此操作。

{
    // use the Cents constructor and operator+(int, int)
    return Cents(c1.m_nCents + c2.m_nCents);
} */

#endif  // CENTS_HPP

答案 1 :(得分:1)

似乎除了带有main的模块之外,类定义还用在另一个模块中。在这种情况下,operator +将被定义两次。您必须从头文件中删除操作员定义并将其放在某个模块中。

答案 2 :(得分:1)

Cents operator+(const Cents &c1, const Cents &c2)以多个代码单位定义。在main.cpp和operatorOverload.cpp中。添加inline以解决此问题或将定义移至operatorOverload.cpp,因此:

// note: this function is not a member function!
inline Cents operator+(const Cents &c1, const Cents &c2)
{
    // use the Cents constructor and operator+(int, int)
    return Cents(c1.m_nCents + c2.m_nCents);
}