【问题标题】:Can't pass a string argument into a constructor? [duplicate]不能将字符串参数传递给构造函数? [复制]
【发布时间】:2018-08-31 09:01:52
【问题描述】:

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

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

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

#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;
}

非常感谢任何帮助!

【问题讨论】:

  • 提示:C++ [在此处插入版本] 是否“继承构造函数”?
  • 代码中的错误不仅仅是缺少 Dog 和 Cat 的构造函数。投票决定重新开放。
  • ideone.com/XptrrQ 应该这样做

标签: c++ constructor


【解决方案1】:

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

由于 using (C++11 起),您可能会使用 Base 构造函数:

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

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

Demo

【讨论】:

  • 除了“构造函数继承”之外,还有更多错误。
  • @AdrianoMartins:确实,override 也是错误的,因为 constness。
猜你喜欢
  • 2023-03-26
  • 1970-01-01
  • 2012-09-11
  • 1970-01-01
  • 2014-08-13
  • 1970-01-01
  • 1970-01-01
  • 2011-12-22
  • 1970-01-01
相关资源
最近更新 更多