我不明白一个人的想法。我有一个名为“ network.h”的头文件,并且带有函数的类声明。在“ network.cpp”文件中,我具有这些功能。当要在main.cpp中包含“ network.h”并编译我的项目(Microsoft Visual Studio 2007)时,出现以下消息:network.obj : error LNK2005: "class networkClass network" (?network@@3VnetworkClass@@A) already defined in main.obj
我知道我们不能例如创建两个相同的变量,但是在此我不知道出了什么问题。
资源:
网络
#ifndef H_NETWORK
#define H_NETWORK
#include <string>
#include <SFML/Network.hpp>
struct getClientsStruct
{
std::string nick;
sf::IpAddress clientIp;
};
getClientsStruct receiveClientIfno();
class networkClass
{
public:
void sendMyInfo();
void bind();
getClientsStruct receiveClientIfno();
};
networkClass network;
#endif
network.cpp
#include <SFML/Network.hpp>
#include "network.h"
#include <iostream>
#include <string>
sf::UdpSocket searchSocket;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
void sendMyInfo()
{
sf::UdpSocket searchSocket;
std::string myLocalAddress = sf::IpAddress::getLocalAddress().toString();
char dataSend[100] = "DANE.......";
sf::IpAddress recipient = "255.255.255.255";
unsigned short portSending = 54000;
if (searchSocket.send(dataSend, 100, recipient, portSending) != sf::Socket::Done)
{
// error...
std::cout << "Sending ERROR" << std::endl;
}
else
std::cout << "Sending SUCCESSED" << std::endl;
}
void bind()
{
// bind the socket to a port
if (searchSocket.bind(54000) != sf::Socket::Done)
{
std::cout << "ERROR binding" << std::endl;
}
else
std::cout << "BIND success" << std::endl;
}
getClientsStruct receiveClientIfno()
{
getClientsStruct ClientInfo;
searchSocket.setBlocking(0);
char dataReceived[100];
std::size_t received;
sf::IpAddress sender;
unsigned short portReceive;
if (searchSocket.receive(dataReceived, 100, received, sender, portReceive) != sf::Socket::Done)
{ // error...
std::cout << "Receive ERROR" << std::endl;
}
std::cout << "Received " << received << " bytes from " << sender << " on port " << portReceive << std::endl;
return ClientInfo;
}
- - - - - - - - - - - - - - - - - 编辑 - - - - - - - - ----------------------
因此,我从network.h中删除了
networkClass network;
,并在main.cpp中对其进行了声明。现在,当我想运行例如network.bind();
的功能时,出现错误:main.obj : error LNK2019: unresolved external symbol "public: void __thiscall networkClass::bind(void)" (?bind@networkClass@@QAEXXZ) referenced in function _main
最佳答案
标头应包含在多个编译单元(cpp文件)中。不幸的是,您在network.h
中定义了一个全局对象network
。因此,它将被声明多次(一次是在编译network.cpp时,另一次是在编译main.cpp时)。
全局变量(如果不能通过其他方式避免它们)应该仅以extern的形式出现在标题中:
extern networkClass network; // you say this variable exist somewhere else
然后,您必须将定义放入一个cpp文件中。顺便说一句,如果您的类不是绝对需要它,则不应在类标题中定义它。而是在main.cpp中定义它。而且,如果您完全可以避免使用全局变量,请摆脱它。
network.cpp
中的另一个问题是您的语法定义了独立于全局类的全局函数。每当在类之外定义类函数时,都必须在其名称前加上类名称。例如:void networkClass::bind() // say which class the function is a member
...
关于c++ - 已经定义的C++类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30278789/