【问题标题】:C++: No matching function call to base class functionC++:没有对基类函数的匹配函数调用
【发布时间】:2015-06-07 08:03:41
【问题描述】:
 class Dobberman: public Dog
    {
    public:
        Dobberman()
            : Dog()
        {
            strncpy(_breed, "Dobberman", 20);
        }
        Dobberman( const char *name, const unsigned int age, const unsigned int pedigreeNo)
            : Dog(name,age), _pedigreeNo(pedigreeNo)
        {
        }
        ~Dobberman()
        {
        }

我在尝试编译时收到上述错误。老实说,不知道为什么。

【问题讨论】:

  • 请添加错误
  • 如果在赋值范围内允许,我建议用 std::strings 替换 char 数组。以后你会感谢自己的。如果您不能使用字符串,请将所有 20s 替换为一个常量,这样您就不会因为在更改数组大小时丢失一个而被钉死。
  • 请发布错误。不是某个链接。
  • 已回答问题。请不要再发表评论。

标签: c++ class inheritance


【解决方案1】:

Class Dog 有一个带三个参数的构造函数

 Dog(const char *name, const unsigned int age, char *breed)

但是在 Dobberman 类的构造函数中,你调用了带有两个参数而不是三个参数的 Dog 构造函数

Dobberman( const char *name, const unsigned int age, const unsigned int pedigreeNo) 
    : Dog(name,age), _pedigreeNo(pedigreeNo) { } 
      ^^^^^^^^^^^^^

因此编译器发出一个错误,即在类Dog 中找不到带有两个参数的构造函数。

考虑到在任何情况下这个构造函数

Dog(const char *name, const unsigned int age, char *breed)
{
    strncpy(_name, name, 20);
    _age = age;
    strncpy(_breed, breed, 20);
}

定义不正确。对于第三个参数,您使用字符串文字作为参数。所以第三个参数必须声明为const char *breed

在构造函数的主体而不是

    strncpy(_name, name, 20);
    strncpy(_breed, breed, 20);

你必须写

    strncpy(_name, name, 20);
    _name[19] = '\0';
    strncpy(_breed, breed, 20);
    _breed[19] = '\0';

Dog 类的也应该声明为虚拟的。例如

virtual ~Dog() {}

virtual ~Dog() = default;

【讨论】:

    猜你喜欢
    • 2016-01-31
    • 2017-05-08
    • 2021-09-21
    • 2016-11-23
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    相关资源
    最近更新 更多