无法将字符串参数传递给构造函数?

时间:2018-03-22 03:14:10

标签: c++ constructor

当我尝试运行我的程序时,它打印出来

  

“错误:没有匹配函数来调用Dog::Dog(const char [4], const char [5])”。

这发生在第60和61行。是否将参数作为C-String读取?我仍然可以将它传递给构造函数,不是吗?

#include <iostream>
#include <string>

using namespace std;

#include <string>
class Pet
{
protected:
    string type;
    string name;
public:
    Pet(const string& arg1, const string& arg2);
    virtual void whoAmI() const;
    virtual string speak() const = 0;
};

Pet::Pet(const string& arg1, const string& arg2): type(arg1), name(arg2)


{}
void Pet::whoAmI() const
{
    cout << "I am an excellent " << type << " and you may refer to me as " << name << endl;
}

class Dog : public Pet
{
public:
    void whoAmI() const;  // override the describe() function
    string speak();

};

string Dog::speak()
{
    return "Arf!";
}

class Cat : public Pet
{
   string speak();
    // Do not override the whoAmI() function
};

string Cat::speak()
{
    return "Meow!";
}

ostream& operator<<(ostream& out, const Pet& p)
{
    p.whoAmI();
    out << "I say " << p.speak();
    return out;
}

int main()
{
    Dog spot("dog","Spot");
    Cat socks("cat","Socks");
    Pet* ptr = &spot;
    cout << *ptr << endl;
    ptr = &socks;
    cout << *ptr << endl;
}

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

Pet构造函数采用2个字符串,而不是Dog

由于使用(自C ++ 11以来),您可以使用Base构造函数:

class Dog : public Pet
{
public:
    using Pet::Pet;

    void whoAmI() const;  // override the describe() function
    string speak();
};

Demo