TIL that variable can be defined like a function call in C++ [duplicate]
I am new to C++.
While I was going through C++ materia开发者_如何学Pythonls, I found that variables in C++ can be defined similar to function calls.
i.e.
int var = 10; //explicit assignment
is same as,
int var(10); //implicit assignment
"Even though implicit assignments look a lot like function calls, the compiler keeps track of which names are variables and which are functions so that they can be resolved properly."Link
Wouldn't it confuse programmers? Why are such features present in C++!!! What are similar confusing features of C++ which I should be aware of ?
It's the same syntax as calling a constructor of an object, so you can use builtin types with templates.
// Not useful, but for example:
class Foo
{
public:
explicit Foo(int num) { }
// ...
};
template <class T>
int bar()
{
T item(5);
}
int main()
{
bar<int>();
bar<Foo>();
return 0;
}
it looks more like a constructor call than a function call actually ;) this is useful when members of a class are given values during object construction. let me give an example:
#include <iostream>
class Cool
{
public:
Cool(std::string someString, bool isCool);
~Cool();
std::string getSomeString() const;
bool isCool() const;
private:
std::string m_someString;
bool m_isCool;
};
Cool::Cool(std::string someString, bool isCool) :
m_someString(someString),
m_isCool(isCool)
{
std::cout << "constructor of Cool, members are set in initialization list\n";
}
Cool::~Cool()
{
std::cout << "destructor of Cool\n";
}
std::string Cool::getSomeString() const
{
return m_someString;
}
bool Cool::isCool() const
{
return m_isCool;
}
int main(int argc, char* argv[])
{
Cool stuff("is cool", true);
if(stuff.isCool())
{
std::cout << stuff.getSomeString();
}
return 0;
}
this feature makes the difference between primitive types and your own types (declared in classes, structs or unions) less... different ;)
remember that the initialization list should first declare super constructors, in the same order as they are declared in the inheritance list, and then the members, in the same order they are declared under private. yes, all members are always declared under private!
the keyword const, specified after a method name inside a class, means that this method promises not to change any of the members in the object. if any of these two methods would assign to any of the members, there would be a compile error. this helps the programmer to not make stupid mistakes in the code, and it also speeds up execution as this lets the compiler make some nice speedy things in the generated binary code.
for more info on the quirks of this amazing language, please read scott meyers' 320 pages short book "effective c++: 55 specific ways to to improve your programs and designs". make sure you're reading the 3rd edition d(^-^)b
精彩评论