gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:03:46 25 4
gpt4 key购买 nike

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

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

这是我的代码:

类.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)

最佳答案

尝试使用预处理器指令隔离您的 header ,并且永远不要在 header 中定义实现:

#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

关于c++ - 使用 .h 文件中定义的 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25223647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com