受保护部分:没有匹配函数可调用

Protected section: no matching function to call

本文关键字:函数 调用 受保护部      更新时间:2023-10-16

有人可以告诉我为什么这段代码不起作用吗?我得到:没有匹配函数调用"孩子::孩子()"错误。如何正确将这个孩子放入受保护的部分?:(

class Child
{
protected:
    int cAge;
public:
    Child(int c)
    {
        this->cAge=c;
    }
};
class Parent
{
protected:
    int pAge;
    Child child;
public:
    Parent(int d)
    {
        this->pAge=d;
    }
};
int main()
{
}

它与"受保护的部分"无关。应使用成员初始值设定项列表指定要调用的类Child的构造函数:

class Parent
{
// ...
public:
    Parent(int d) : child(d)
//                ~~~~~~~~~~
    {
        this->pAge=d;
    }
};

否则,默认构造函数为 Child(即 Child::Child() ) 将尝试调用,但它不存在。