Reputation: 2353
I am writing a simple client / server program to mess around with socket programming. I made two classes, one for the client and one for the server. I can run my server with no problems and also my client can connect. But now I am attempting to modify my client so it accepts the hostname and port number in the constructor.
Here is what I have so far (client.h class only the constructor and attributes):
#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
I am having a hard time setting the char * hostname
from the constructor. I am obviously having a little trouble with pointers and references. Can someone help me out here, coding mostly in PHP for the past 5 years has made my C++ rusty...
Here is the C++ file I use the client.h class.
#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;
}
Thanks!
Upvotes: 1
Views: 5783
Reputation: 1
class Mahasiswa{
public:
char nama[1000];
double tinggi,berat,imb;
Mahasiswa *next;
Mahasiswa(char* nama,double tinggi,double berat){
Mahasiswa::nama = nama;
Mahasiswa::tinggi = tinggi;
Mahasiswa::berat = berat;
}
double HasilBmi(){
double tinggi_meter = tinggi / 100;
imb = berat/(tinggi_meter*tinggi_meter);
return imb;
}
char* Getname(char* nama){
return nama;
}
};
Upvotes: 0
Reputation: 35990
If you're going to be coding in C++ may I suggest using std::string instead of char pointers?
class Client
{
public:
Client(const string& in_hostname, int in_port)
: hostname(in_hostname), port(in_port)
{
}
~Client() {}
private:
std::string hostname;
int port;
};
Edit:
In response to your comment. If you have to pass the pointer around to another function you can get it from std::string::c_str
std::string stuff;
stuff.c_str();
Upvotes: 7
Reputation: 92924
I am having a hard time setting the
char * hostname
from the constructer.
Change &in_hostname
to in_hostname
Client(char *in_hostname, int in_port)
: hostname(in_hostname), port(in_port)
{
}
However if you want your code to be clean you should use std::string
(C++ style string) instead of (char *
) i.e C style string
Upvotes: 3