在构造函数中设置C ++类char *

时间:2011-01-22 17:45:40

标签: c++ pointers

我正在编写一个简单的客户端/服务器程序来解决套接字编程问题。我创建了两个类,一个用于客户端,另一个用于服务器。我可以毫无问题地运行我的服务器,我的客户端也可以连接。但现在我正在尝试修改我的客户端,因此它接受构造函数中的主机名和端口号。

这是我到目前为止(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

我很难从构造函数中设置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;
}

谢谢!

2 个答案:

答案 0 :(得分:7)

如果你要用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;
};

编辑:

回应你的评论。如果你必须将指针传递给另一个函数,你可以从std :: string :: c_str

获取它
std::string stuff;
stuff.c_str();

答案 1 :(得分:3)

  

我很难从构造函数中设置char * hostname

&in_hostname更改为in_hostname

Client(char *in_hostname, int in_port)
        : hostname(in_hostname), port(in_port)
    {

    }

但是,如果您希望代码清洁,则应使用std::string(C ++样式字符串)代替(char *),即C样式字符串