Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
The purpose of extern is the only one. We say that this variable is not in this compilation unit, but don't worry, it is in another one and the linker will sublink it.
In fact, it is an extern static field of the class. This decision was made by Stroustrup for a simple reason: the class definition can flash several times in different compilation units, and the variable definition must be one per program.
If your code does not work without extern, it means that a global variable called client was found somewhere, and for the webmaster to work correctly, it was necessary to contact this client of ours. In fact, a very fancy way to create a static field.
Thus, you have three options.
1. If there is only one Ethernet client for all webmasters, you need a static field.
// HEADER
class WebMaster {
public:
WebMaster();
bool connect_open();
private:
static EthernetClient client;
}
// CPP
EthernetClient WebMaster::client;
class WebMaster {
public:
WebMaster();
bool connect_open();
private:
EthernetClient client;
}
// HEADER
class WebMaster {
public:
WebMaster(EthernetClient& aClient);
bool connect_open();
private:
EthernetClient& client;
}
// CPP
WebMaster::WebMaster(EthernetClient& aClient) : client(aClient) {}
...
EthernetClient client;
WebMaster webmaster(client);
class WebMaster {
public:
EthernetClient client;
WebMaster();
}
WebMaster::WebMaster() {
}
bool WebMaster::connect_open() {
byte addr[4]= {xx,xx,xx,xx};
if (client.connect(addr, 80)) {
return true;
}
else{
return false;
}
}
Strange decision. Why not instantiate the class internally? Or inherit from it?
Or
EthernetClient client;
WebMaster master1;
WebMaster master2;
master1.setClient(client);
master2.setClient(client);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question