C ++ coding technology: Why avoid single-parameter constructor?

Source: Internet
Author: User

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 A {public: string type () const {return "A" ;}}; class B {public: B () {cout <"B () "<endl;} B (A a) {cout <" B (A a) "<endl ;} // This code causes A to automatically construct B string type () const {return "B" ;}}; ostream & operator <(ostream & OS, const B & tmp) {return OS <tmp. type () <"" <& tmp;} void defaulttest () {A a; B B; cout <B. type () <"" <& B <endl; cout <. type () <"" <& a <endl; cout <a <endl;} output: B () B 0xfffffffffefb1b bytes ----------------- cou <bA Qu (A) B 0xfffffffffffeff8 ------------------- cout <a it is obvious that B is a newly constructed deletion B (A) compilation error, this is the correct result: "operator <(ostream &, const B &)" is not a viable candidate. (example code running environment: ibm aix, xlC)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.