问题
I would like to add a Child class to a pre-existing project having Parent already defined and declared. Parent class has got two constructors with initializer-list. This is my code, and it generates error C2668: 'Parent::Parent' : ambiguous call to overloaded function. Where is my error?
Thanks @Mape for your snippet
#include <stdio.h>
class Parent
{
public:
// Here a constructor with one default trailing argument, i.e. myInt,
// myDouble is not initialised. This is correct, as once one argument
// is initialised, the rule is that all the following ones have to be
// initialised, but the previous ones may not be.
Parent(double myDouble, int myInt=5);
// Here a defauls contructor, as all its arguments (one indeed) are
// initialised
Parent(double myDouble=0);
double m_dVar;
int m_iVar;
};
class Child : public Parent
{
public:
// derived class has to redefine the constructors.
// Q1: All of them?
// Q2: With the same default arguments?
Child(double myDouble, int myInt=0);
Child(double myDouble=0);
};
class User
{
public:
User();
Parent* m_pGuy;
Child* m_pSonOfGuy;
};
// Base Class Implementation
Parent::Parent(double myDouble, int myInt)
{
m_dVar=myDouble;
m_iVar=myInt;
}
Parent::Parent(double myDouble)
{
m_dVar=myDouble;
m_iVar=3;
}
// Derived Class Implementation
// the two arguments contructor is easily implemented.
Child::Child(double myDouble, int myInt)
: Parent(myDouble*2, myInt+1)
{
}
// the one argument contructor may trigger ERROR:
// "ambiguous call to overloaded function."
// (C2668 in Microsoft Visual Studio compiler)
Child::Child(double myDouble)
//: Parent(0) ERROR
: Parent() //OK
{
m_iVar=9;
}
User::User()
: m_pGuy(0)
{
}
// main{
int main(void)
{
User user1();
//Parent parent;
Child child1(8.3,1);
printf("\n\nChild m_dVar %f",child1.m_dVar);
printf("\nChild m_iVar %d",child1.m_iVar);
return 0;
}
回答1:
Compiler doesn't know which constructor you intend to call.
For example, your Parent
class constructors, when called with one parameter, really have the same function signature.
Parent::Parent(double myDouble, int myInt=0) {
cout << "Foo";
}
Parent::Parent(double myDouble) {
cout << "Bar";
}
// later
Parent *parent = new Parent(1.2345); // Compiler: which constructor to call?
// does this mean Parent(1.2345, 0)
// or Parent(1.2345)
Is this suppose to print Foo or Bar?
To make it work
- Change the code so that
myInt
parameter is not optional.
OR
- Remove the other constructor which only takes
myDouble
as parameter.
来源:https://stackoverflow.com/questions/48720199/overloaded-parent-class-constructors-wrong-inizializer-choice