c++ constructor question -
i still confused ctors:
question 1:
why line 15 call a:a(int) instead of a:a(double&)?
question 2:
why line 18 did not call a:a(b&)?
#include <iostream> using namespace std; class b{}; class a{ public: a(int ) {cout<<"a::a(int)"<<endl;} a(double&){cout<<"a::a(double&)"<<endl;} // work if a(double), without & a(b&){cout<<"a::a(b&)"<<endl;} }; int main() { /*line 15*/ obj((double)2.1); // call a(int), why? b obj2; obj3(obj2); /*line 18*/ obj4(b); // did not trigger output why? }
line 15: a(double&) can take lvalues, i.e. variables can assigned to. (double)2.1 rvalue. use a(const double&) if need accept rvalues reference too.
line 18: b type, not value. a obj4(b); declares function name obj4 taking b , returning a.
Comments
Post a Comment