gpt4 book ai didi

c++ - 仅使用 getName 在主函数中设置字符串名称

转载 作者:太空宇宙 更新时间:2023-11-04 13:03:00 24 4
gpt4 key购买 nike

我正在使用展示多态性的子类进行作业。该程序需要为每个新对象指定一个名称。我只应该有 string getName(){return name;} (这位于基类中)。每个类 class(string){} 中还有一个构造函数。在主函数中,我想为每个对象设置名称。非常感谢我应该如何做的任何建议!

h 文件:

#ifndef DUCK_H
#define DUCK_H
#include <string>
using namespace std;

class Duck
{
private:
string name;
public:
Duck(){}
Duck(string){}
string getName() { return name; };
virtual string quack() {return "Which"; }
virtual string fly() { return "How?"; }
};
class RubberDuck : public Duck
{
public:
RubberDuck(){}
RubberDuck(string) {}
string quack() { return "Squeak"; }
string fly() { return "Fly with bounce"; }
};
class MallardDuck : public Duck
{
public:
MallardDuck(){}
MallardDuck(string) {}
string quack() { return "Quack"; }
string fly() { return "Fly with wings"; }
};
class RocketDuck : public Duck
{
public:
RocketDuck(){}
RocketDuck(string) {}
string quack() { return "Zoom"; }
string fly() { return "Fly with rockets"; }
};
#endif // !1

cpp文件:

#include <iostream>
#include "Duck.h"
using namespace std;

//void display(Duck *d);

int main()
{
Duck d1;
MallardDuck md;
RubberDuck rbd;
RocketDuck rd;

//for main duck
//Duck duck("Donald");
//cout << duck.getName();
cout << d1.quack() <<"\n";
cout << d1.fly() <<"\n";
cout << "\n";
//for rubber duck
RubberDuck rbdname("Rubby");
cout << rbd.quack() << "\n";
cout << rbd.fly() << "\n";
cout << "\n";
//for mallard duck
MallardDuck mdname("Mally");
cout << md.quack() << "\n";
cout << md.fly() << "\n";
cout << "\n";
// for rocket duck
RocketDuck rdname("Rocky");
cout << rd.quack() << "\n";
cout << rd.fly() << "\n";
cout << "\n";
//polymorphism
Duck *d2 = new MallardDuck();
cout << d2->getName() << "\n";
cout << d2->quack() << "\n";
cout << d2->fly() << "\n";
cout << "\n";

return 0;
}
/*void display(Duck d)
{
cout << d.quack();
}
*/

最佳答案

您是在问如何调用您定义的构造函数吗?你会那样做

Duck duck("Drake Mallard");

关于c++ - 仅使用 getName 在主函数中设置字符串名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43443608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com