gpt4 book ai didi

c++ - 子类中的重载运算符

转载 作者:行者123 更新时间:2023-11-30 02:51:54 25 4
gpt4 key购买 nike

参观和导游。导览扩大旅游档次。我在旅游类中重载了 << 和 >> 运算符。

我的旅游类长这样

#include <iostream>
#include <vector>
#include "Customer.h"

using namespace std;

class Tour {

protected:
string id;
string description;
double fee;
vector<string> customerList;

public:
Tour();
Tour(string idVal, string descriptionVal, double feeVal);
string getId();
string getDescription();
double getFee();
double getTotalForTour();
virtual void addCustomer(string cust);
vector<string> getCustomers();
virtual void display();

friend ostream& operator<< (ostream &out, Tour &cust);
friend istream& operator>> (istream &in, Tour &cust);
};

那么我的导览是这样的,

#include <iostream>
#include "Tour.h"
#include "SimpleDate.h"

using namespace std;

class GuidedTour : public Tour {

private:
SimpleDate* date;
string guideName;
int maxNumTourists;

public:
GuidedTour();
GuidedTour(string idVal, string descriptionVal, double feeVal, SimpleDate* dateVal, string guideNameVal, int maxNumTouristsVal);
virtual void addCustomer(string cust);
SimpleDate* getDate();
void display();

friend ostream& operator<< (ostream &out, GuidedTour &cust);
friend istream& operator>> (istream &in, GuidedTour &cust);
};

我想在子类上以不同方式重载这些运算符以执行其他操作。

我有一个包含游览和导游的 vector 。

当我循环遍历 vector 并执行以下操作时,

for (unsigned int i = 0; i < tourListVector.size(); i++) {

cout << *tourListVector[i];
}

它始终执行游览中指定的操作,即使对象是导游也是如此。

你能帮忙吗?

最佳答案

您几乎做对了,但不完全正确。让我们先来看看输出案例——输入案例的工作原理是一样的。

首先,你应该声明一个

virtual void write(std::ostream&) const;

基类中的成员函数。实现可能类似于:

void Tour::write(std::ostream& os) const
{
os << "ID: " << id << std::endl;
os << "Description: " << description << std::endl;
// etc
}

我假设这是您当前在 operator<<(ostream&, Tour&) 中的代码类型.然后你需要在你的派生类中重载它——也许用类似的东西

void GuidedTour::write(std::ostream& os) const
{
Tour::write(os); // Write out base Tour info first
os << "Guide Name: " << guideName << std::endl;
// etc
}

之后,您可以声明一个免费(即非成员(member))operator<< Tour 过载s,它调用你的 write()成员函数,比如

std::ostream& operator<<(std::ostream& os, const Tour& tour)
{
tour.write(os);
return os;
}

例如。

解释:忘记你当前的operator<<是 friend ;在这种情况下它没有影响。相反,假设您有两个重载的非成员函数,称为

void do_something(Tour& t); // (a)
void do_something(GuidedTour& gt); // (b)

由于您的 tourListVector包含(我假设)Tour*指针,如果你要遍历 vector 并调用 do_something()在每个元素上,编译器只能匹配上面的函数 (a)。那是因为它无法知道某些 Tour*对于给定的程序运行,指针实际上可能指向 GuidedTour实例。为了像这样进行运行时调度,您需要使用虚函数。

旁白:(我知道这是示例代码,但如果您是 C++ 的新手,那么值得指出,以防您不知道:-))

因为您正在使用 Tour*指针,你应该为你的基类定义一个虚拟析构函数。如果不这样做,编译器将不知道它可能需要销毁 GuidedTour 的所有成员。打电话时上课 deleteTour* 上.事实上,如果您的类包含任何其他虚函数,那么将析构函数设为虚函数通常是一种很好的做法,只是为了避免以后出现潜在问题。

此外,请不要输入 using namespace std;在头文件中:-)

关于c++ - 子类中的重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19376943/

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