I was given a c++ main and have to code it so it works.
I am having some trouble understanding the code as I am a bit new to cpp.
Here is the code
int main(int argc, char *argv[]) {
Class::setAtribute("string");
Class(Class::CONSTANT) << "starting up...";
}
Some questions:
-
How can the first line work with no variables? Is it static?
-
The second line is really strange for me, what I can make out is a Constructor that takes in a class constante and then prints it out somehow?
If someone could explain me this bit of code it would be great!
Thanks in advance.
Class::setAtribute()must be a static function in classClass. A static function doesn’t need an instance of a class (object).Right, it constructs an instance of
ClasspassingClass::CONSTANTas the argument toClassconstructor. ForClass(Class::CONSTANT) << "starting up...";to compile there must be an overloadedoperator<<in the form of:As a member function of
Class(David Rodríguez – dribeas):or as a free-standing function:
or:
or, in C++11:
The second argument, in fact, can be anything that can be constructed from a string literal
char const[]. Or, alternatively,Classcan have a conversion operator to, say,std::ostream&, so thatstd::ostream& std::operator<<(std::ostream&, char const*)is picked instead. Looking atClassdefinition and free-standing functions in its namespace must yield a definite answer.