gpt4 book ai didi

c++ - 构建基本 C++ 程序时出现 "multiply defined symbols found"

转载 作者:行者123 更新时间:2023-11-28 00:54:34 25 4
gpt4 key购买 nike

我是 C++ 新手。

所以我正在创建一个程序,该程序收集然后显示有关书籍等的信息。首先,我想更多地了解我正在做的代码,但我不熟悉 C++ 错误代码。

我创建了 2 个类 Book 和 Publisher,每个类都包含自己的构造函数和方法。在我尝试使我的程序包含我在类图中给出的所有类和方法之后,当我收到错误消息时我停止了:

1>Publisher.obj : error LNK2005: "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl getPublisherInfo(void)" (?getPublisherInfo@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) already defined in Book.obj
1>Publisher.obj : error LNK2005: "void __cdecl setAddress(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?setAddress@@YAXV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) already defined in Book.obj
1>Publisher.obj : error LNK2005: "void __cdecl setCity(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?setCity@@YAXV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) already defined in Book.obj
1>Publisher.obj : error LNK2005: "void __cdecl setName(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?setName@@YAXV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) already defined in Book.obj
1>C:\Users\pc\Desktop\School\ITS 340\Labs\Lab 1\Lab 1\Debug\Lab 1.exe : fatal error LNK1169: one or more multiply defined symbols found

这是我的 Publisher.cpp 文件:

#include <iostream>
using namespace std;

class Publisher
{
public:
Publisher();
Publisher(string name, string address, string city);
string getPublisherInfo();
void setName(string name);
void setAddress(string address);
void setCity(string city);

private:
string name;
string address;
string city;
};

Publisher::Publisher()
{
}

Publisher::Publisher(string name, string address, string city)
{
}

string getPublisherInfo()
{
return 0;
}

void setName(string name)
{
}

void setAddress(string address)
{
}

void setCity(string city)
{
}

我怎样才能避免这个错误?

最佳答案

你正在破坏 one definition rule .您需要在头文件中声明类和函数,用 include guards 保护它们,并且只将函数和类成员函数的实现或定义放在.cpp文件中。

例如:

Foo.h:

#ifndef FOO_H_
#define FOO_H_
class Foo {
Foo();
void foo() const;
};
#endif

Foo.cpp:

#include "Foo.h"
Foo::Foo() { .... }
void Foo::foo() const { .... }

主要.cpp

#include "Foo.h"
int main()
{
Foo f;
f.foo();
}

这完全独立于 OOP。您必须对免费功能执行相同的操作。

关于c++ - 构建基本 C++ 程序时出现 "multiply defined symbols found",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12229407/

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