无法将字符串参数传递到构造函数中?
Can't pass a string argument into a constructor?
当我尝试运行我的程序时,它会打印出来
"错误:调用
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;
}
任何帮助将不胜感激!
Pet
构造函数需要 2 个字符串,而不是 Dog
个。
你可以使用 Base 构造函数,这要归功于使用(自 C++11 起(:
class Dog : public Pet
{
public:
using Pet::Pet;
void whoAmI() const; // override the describe() function
string speak();
};
演示
相关文章:
- 在执行new期间是否可以在构造函数中传递不同的参数?
- shared_ptr构造函数参数是否应按值传递
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- 将派生类构造函数参数传递给受保护的成员
- 在构造函数上传递参数或在每个方法上传递参数
- 如何将变量作为构造函数参数或函数参数传递
- 当数组对象以函数参数传递时,为什么复制构造函数会自称
- 示例自定义共享_ptr-我如何传递构造函数参数 - 我在此处使用variadic模板
- 引用成员到构造函数参数按值传递
- C++将Lambda函数作为类构造函数参数传递
- C :在构造函数中传递指针类参数
- c++在创建时将构造函数参数从父对象传递到子对象
- 在具有boost工厂的构造函数中传递参数
- 在构造函数中传递枚举作为参数
- 将字符串构造作为函数参数传递
- 将构造函数参数传递给模板函数工厂
- 如何删除在 c++ 中作为构造函数参数传递的已分配变量
- 不能正确识别作为构造函数参数传递的函数
- 将方法作为构造函数参数传递
- 为每个可变模板参数调用函数,并将结果作为构造函数参数传递