简体   繁体   中英

constructor with one default parameter

Suppose I have a class

class C {
       C(int a=10);
};

why if I call

C c;

the contructor C(int =10) is called and if I call

C c();

the default constructor is called? How to avoid this? I want to execute only my constructor, I tried to make the default constructor private, but it doesn't work.

  1. Actually, C c(); should be parsed as a function declaration . In order to explicitly invoke the default-constructor, you need to write C c = C(); .
  2. Once you define any constructor, the compiler will not provide a default-constructor for your type, so none could be called.
  3. Since your constructor can be invoked with one argument, it serves as an implicit conversion function. You should consider making it explicit , to prevent implicit conversions from kicking in at unexpected moments.

The code C c(); doesn't do what you think it does:

It declares a function called c that takes no arguments and returns a C . It is equivalent to

C c(void);

This is because the c() is interpreted as a function named c . C() will trigger the appropriate constructor for the C class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM