c++ - Passing an object to a function taking a reference, an interview test -
i had interesting (or stupid) interview question. well, know code below not compile, not give answer on how modify class c make code compile. told answers test(c(1));
or void test(c c)
unacceptable. can me?
here's question:
q11. following code compile? if not, make changes want class c in order code compile.
class c { public: c(int i) {} ~c() {} }; void test(c &c) { } int main(int, char*) { test(1); return 0; }
the code not compile.
there no way make compile changing class c
first because signature main
wrong (char* never type of second argument).
but if signature of main
correct test(1);
wants implicitly create temporary object of c
, pass test
. however, cannot bind temporary non-const reference, , can't see way change class c
create implicit temporary can bind parameter test
.
edit: closest i've come putting friend void test(int i) { }
c
. compile sun's cc compiler fails compile g++ 4.4, 4.5, or 4.8 ideone. edit2: appears 11.4/5 g++ correct here: function introduced scope of class, not enclosing scope.
Comments
Post a Comment