A temporary object can only be bound with a constant reference. In this case, only constant functions can be called for constant reference.
However, you can directly call member functions on a temporary object (if there are non-constant functions and constant functions, the call of non-constant functions is preferred ).
- # Include <stdio. h>
- # Include <iostream>
- Using namespace STD;
- Class {
- Public:
- Virtual void func (INT data) {printf ("A1: % d/N", data );}
- Virtual void func (INT data) const {printf ("A2: % d/N", data );}
- };
- Void func (const A & T)
- {
- T. func (10 );
- Cout <"func is called! "<Endl;
- }
- A test ()
- {
- Return ();
- }
- Int main ()
- {
- // A & A = a (); // error, a () returns a temporary object and can only be bound with a constant reference.
- Const A & A = a (); // seccessful
- A. func (20); // call a constant function
- Func (());
- A (). func (1); // call a very large number of functions (if any)
- Test (). func (100); // call a very large number of functions (if any)
- Return 0;
- }