我正在编写一个简单的客户端/服务器程序来解决套接字编程问题.我创建了两个类,一个用于客户端,另一个用于服务器.我可以毫无问题地运行我的服务器,我的客户端也可以连接.但现在我正在尝试修改我的客户端,因此它接受构造函数中的主机名和端口号.
这是我到目前为止(client.h类只有构造函数和属性):
#ifndef CLIENT_H
#define CLIENT_H
class Client
{
public:
Client(char *in_hostname, int in_port)
: hostname(&in_hostname), port(in_port)
{
}
~Client() {}
private:
char *hostname;
int port;
};
#endif
Run Code Online (Sandbox Code Playgroud)
我很难设置char * hostname构造函数.我显然对指针和引用有点麻烦.有人可以帮我解决这个问题,在过去的5年里,大部分用PHP编写的代码让我的C++变得生疏......
这是我使用client.h类的C++文件.
#include <iostream>
#include "client.h"
using namespace std;
int main (int argc, char * const argv[])
{
char * hostname;
int port;
if(argc == 3)
{
hostname = argv[1];
port = argv[2];
Client *client = new Client(hostname, port);
delete(client);
}
else
{
cout << "Usage: ./client hostname port" << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
如果您要使用C++进行编码,我建议使用std :: string而不是char指针?
class Client
{
public:
Client(const string& in_hostname, int in_port)
: hostname(in_hostname), port(in_port)
{
}
~Client() {}
private:
std::string hostname;
int port;
};
Run Code Online (Sandbox Code Playgroud)
编辑:
回应你的评论.如果你必须将指针传递给另一个函数,你可以从std :: string :: c_str获取它
std::string stuff;
stuff.c_str();
Run Code Online (Sandbox Code Playgroud)