我主要的代碼看起來像這樣:「[類別]不名執行文件類型錯誤
#include "ClientSocket.h"
#include "SocketException.h"
#include <iostream>
#include <string>
int main (int argc, char argv[])
{
std::cout << "" << std::endl;
try
{
ClientSocket client_socket ("localhost", 30000);
std::string reply;
try
{
client_socket << "Test message.";
client_socket >> reply;
}
catch (SocketException&) {}
std::cout << "We received this response from the server:\n\"" << reply << "\"\n";;
}
catch (SocketException& e)
{
std::cout << "Exception was caught:" << e.description() << "\n";
}
return 0;
}
頭文件看起來像這樣:
// Definition of the ClientSocket class
#include "ClientSocket.cpp"
#include "Socket.h"
#ifndef _CLIENTSOCKET_H
#define _CLIENTSOCKET_H
class ClientSocket : private Socket
{
public:
ClientSocket (std::string host, int port);
virtual ~ClientSocket(){};
const ClientSocket& operator << (const std::string&) const;
const ClientSocket& operator >> (std::string&) const;
};
#endif
和實施文件看起來像這樣:
// Implementation of the ClientSocket class
#include "Socket.h"
#include "SocketException.h"
ClientSocket::ClientSocket (std::string host, int port)
{
if (! Socket::create())
{
throw SocketException ("Could not create client socket.");
}
if (! Socket::connect (host, port))
{
throw SocketException ("Could not bind to port.");
}
}
const ClientSocket& ClientSocket::operator << (const std::string& s) const
{
if (! Socket::send (s))
{
throw SocketException ("Could not write to socket.");
}
return *this;
}
const ClientSocket& ClientSocket::operator >> (std::string& s) const
{
if (! Socket::recv (s))
{
throw SocketException ("Could not read from socket.");
}
return *this;
}
我發現,編譯這些文件會導致編譯錯誤的木筏在implemen特別是,無論我使用的包含和警衛的組合如何。
In file included from ClientSocket.h:3:0,
from simple_client_main.cpp:1:
ClientSocket.cpp:6:1: error: 'ClientSocket' does not name a type
ClientSocket::ClientSocket (std::string host, int port)
^
ClientSocket.cpp:19:7: error: 'ClientSocket' does not name a type
const ClientSocket& ClientSocket::operator << (const std::string& s) const
^
ClientSocket.cpp:29:7: error: 'ClientSocket' does not name a type
const ClientSocket& ClientSocket::operator >> (std::string& s) const
^
張貼的東西似乎是最有意義的。我試過在實現文件中包含頭文件,它什麼都不做。我試過從頭文件中刪除包含,並在實現文件中包含頭文件,但是這會用未定義的引用錯誤替換'不命名類型'錯誤。代碼中是否存在阻止編譯的內容?
永遠不要包含cpp文件。 –
永遠不要在這種形式下使用頭文件'_CLIENTSOCKET_H' - 只需使用'CLIENTSOCKET_H'。並將標題文件中的標頭守衛放在_everything_附近。 –
以下劃線後跟大寫字母開頭的名稱將保留用於實施。 *永遠不要*在你自己的代碼中使用這樣的名字(甚至不用於頭部守衛)。 –