melo-physique 2020-04-09 22:14 采纳率: 33.3%
浏览 5731

C++ 没有与参数列表匹配的构造函数 ?

C++ 没有与参数列表匹配的构造函数 实例

参数类型为: (const char [12], Boy *)

#include<iostream>
#include<string>
using namespace std;
class Boy:public Person{};
class Girl:public Person{ 
  Girl(string name, Boy &b){
    cout << "Creating a girl named " << name << "." << endl;
    }
};
int main()
{
    Girl g2("Pretty Goat", &b);
        报错:【没有与参数列表匹配的构造函数 实例 
           参数类型为:  (const char [12], Boy *)】
    return 0;
}

只复制了代码片段 为什么会报错没有与参数列表匹配的构造函数?

  • 写回答

2条回答 默认 最新

  • 关注

    Girl(string name, Boy &b)中,b在函数参数列表的声明中,&b指Boy的左值引用。调用该构造函数时,会传递b的引用而不是拷贝b。因此,构造Girl时需要Boy实例。而&b在函数定义中指取b的地址,类型为Boy* 。类型不匹配,所以会报错

    修改方式:在int main中插入Boy b;
    并删去 ,&b) 中的&

    问题解决后,点个已解决,谢谢

    评论

报告相同问题?