Why avoid single-parameter constructor?
The following code defines two classes A and B, which are supported by B <, A does not support (this is an oversight). Normally, this should cause a compilation error, however, because B has a function constructed from a (note that this is beyond the control of a), the code is compiled, but the execution result is completely incomprehensible. If this problem occurs in a large project (that is, the classes and functions involved are distributed in different files in different directories), it cannot be assumed that this problem can be easily solved.
Class
{
Public:
String type () const {return "";}
};
Class B
{
Public:
B () {cout <"B ()" <Endl ;}
B (A) {cout <"B (a)" <Endl ;}// this code causes a to be automatically constructed from B
String type () const {return "B ";}
};
Ostream & operator <(ostream & OS, const B & TMP)
{
Return OS <TMP. Type () <"" <& TMP;
}
Void defaulttest ()
{
A;
B;
Cout <B. Type () <"" <& B <Endl;
Cout <B <Endl;
Cout <Endl;
Cout <A. Type () <"" <& A <Endl;
Cout <A <Endl;
}
Output:
B ()
B 0xfffffffffffefb1
B 0xfffffffffffefb1 ----------------- cou <B
A 0xfffffffffffefb0
B ()
B 0xfffffffffffeff8 ------------------- cout <A it is obvious that B is newly constructed
A compilation error occurs after B (A) is deleted. This is the correct result:
"Operator <(ostream &, const B &)" is not a viable candidate.
(Example code running environment: ibm aix, xlc)