Ambiguity in c++ constructor when a constructor with default argument exists

泪湿孤枕 提交于 2019-12-11 02:39:45

问题


 #include<iostream>
 using namespace std;
 class abc{
    int a;
   public: abc() { } //do nothing constructor
           abc(int x=6){ a=x;} //constructor with default argument  
  };
 main()
  {
      abc a;
    ....
  }

my question is which constructor will be invoked in this case ? Please explain


回答1:


This will not compile due to the ambiguity as you can see here

prog.cpp:8:7: warning: ISO C++ forbids declaration of ‘main’ with no type [-Wreturn-type]
prog.cpp: In function ‘int main()’:
prog.cpp:10:11: error: call of overloaded ‘abc()’ is ambiguous
prog.cpp:10:11: note: candidates are:
prog.cpp:6:12: note: abc::abc(int)
prog.cpp:5:12: note: abc::abc()



回答2:


The call you are making to the constructor is ambiguous. The compiler cannot know which constructor to call since one of your constructor contains a default argument.

Instead, try removing the default value to the argument.



来源:https://stackoverflow.com/questions/17770113/ambiguity-in-c-constructor-when-a-constructor-with-default-argument-exists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!