+ 4
Can cout/cin be considered a function?
I've learned that printf on C is a function,so is it the parenthesis,which become something on a function/method?
4 Respostas
+ 5
No. cout and cin are not functions and it isn't reasonably close to being one.
cout is an instance of a class called ostream. cout is not a function. You could say cout is a variable.
cin is similarly a variable and not a function. cin is an instance of istream.
How operators such as << work on cout is far more like a function but it still wouldn't be called a function in c++. << is an operator. operator overloads can be thought a lot like non-alphanumeric names for functions. In other words, "<<" is a lot like the name of a method except c++ technically calls things with this type of name an operator. Even though c++'s jargon classifies functions and operators separately, I think it is very reasonable to see them as similar. Operators and functions take parameters, execute algorithms, have return values... In other words, cout << "Hello" is a lot like calling printf("hello") or if you can dream of a method being like: cout.print("Hello").
You can see some operator overloading examples here to learn more:
https://en.cppreference.com/w/cpp/language/operators
See how similar an operator overload is to a function definition and implementation.
Java doesn't support operator overloading probably because the designers saw it as duplicating the role of methods. In Java, an "add" method would be added. In c++, operator+ would be implemented. Java supports many operators but their definitions are not overridable like in c++.
+ 2
Eduardo Santana
cout - (c)haracter (out)put - is an object defined by the ostream class.
cin - (c)haracter (in)put - is an object defined by the istream class.
They're declared in the <iostream> header file respectively as:
extern ostream cout;
and
extern istream cin;
As an object, cout has corresponding methods that could be used to take args to write to the output stream:
int length = 15;
cout.write("a char array", length);
Alternatively and more commonly used, cout can be used with the insertion (<<) operator followed by an array of chars to be written to the output stream.
cout << "a char array";
This is similar to cin with the extraction (>>) operator.
You'll want to learn more about operator overloading to understand that the insertion (<<) operator is really a function that overloads the symbol operator using a signature similar to:
ostream& operator<<(ostream& out, const T& obj)
{
// write to stream, then...
return out;
}
Hope this helps your understanding.
0
Thank you very much