简体   繁体   English

我应该如何在 C++ 中重载运算符 +

[英]How am I supposed to overload the operator + in C++

I should be overloading the operator + for adding two squads that will return as a result a new squad with the number of members that is the sum of the number of members of both squads, and other attributes are taken from the squad with larger number of members.我应该重载运算符 + 以添加两个小队,结果将返回一个新小队,其成员数量是两个小队成员数量的总和,其他属性取自具有较大数量的小队成员。 I am trying it but the result does not make any sense!我正在尝试,但结果没有任何意义! And I don't know whether the mistake is in the part where I am overloading the + operator, or it is in the function that shows which tour has most members?!而且我不知道错误是在我重载 + 运算符的部分,还是在显示哪个巡演的成员最多的函数中?!

Here is what all the exercise says: "Mountain squad Problem 2 (0 / 30)以下是所有练习的内容:“山地小队问题 2 (0 / 30)

Write a class for mountain squad, that keeps information for the name of the squad (dynamically allocated array of chars), number of tours (integer) and number of members (integer).为山地小队编写一个类,其中包含小队名称(动态分配的字符数组)、游览次数(整数)和成员数(​​整数)的信息。 For this class implement:对于此类实现:

•operator + for adding two squads that will return as a result a new squad with number of members that is sum of the number of members of both squads, and other attributes are taken from the squad with larger number of members. •operator + 用于添加两个小队,结果将返回一个新小队,其成员数量是两个小队成员数量的总和,其他属性取自成员人数较多的小队。

•operators >, < for comparison by the number of members •operators >, < 用于按成员数进行比较

•operator << for printing the info on SO. •operator << 用于打印 SO 上的信息。

Write a function that accepts array of mountain squads and the size of the array and prints the squad with max number of members.编写一个函数,该函数接受山地小队的数组和数组的大小,并打印具有最大成员数的小队。 "

#include <iostream>
#include <string.h>
using namespace std;

class MSquad{
private:
char *name;
int tours;
int members;
void copy(const MSquad &toCopy){
    name = new char[strlen(toCopy.name) + 1];
    strcpy(name, toCopy.name);
    tours = toCopy.tours;
    members = toCopy.members;
}


public:
MSquad(char *n = "unknown", int nT = 0, int nM = 0){
    name = new char[strlen(n + 1)];
    strcpy(name, n);
    tours = nT;
    members = nM;
}

MSquad(const MSquad &toCopy){
    copy(toCopy);   
}
~MSquad(){
    delete [] name;
}

const MSquad &operator=(const MSquad &right){
    if(&right != this){ // avoiding self- assignment
        delete [] name;
        copy(right);
    }

    return *this;
}

MSquad &operator+(const MSquad &right) const{

    members = members + right.members;
    if(right.members > members){
        name = new char[strlen(right.name) + 1];
        strcpy(name, right.name);
        tours = right.tours;
        //members = members + right.members;
    }
    return *this;

}

bool operator>(const MSquad &right){
    return members > right.members;
}

bool operator<(const MSquad &right){
    return members < right.members;
}

friend ostream &operator<<(ostream &output, const MSquad &right);
friend void mostMembers(MSquad *squads, int size);


};

ostream &operator<<(ostream &output, const MSquad &right){
output << "Name: " << right.name;
output << " Tours: " << right.tours;
output << " Members: " << right.members << endl;
return output;
}
void mostMembers(MSquad squads[], int size){
int max = squads[0].members;
int j = 0;
for(int i = 1; i < size; i++){
    if(squads[i].members >= max){
        max = squads[i].members;
        j = i;
    }
}

cout << "The max number of members is in squad in: " << squads[j] << endl;
}


int main()
{               
MSquad squads[3];
MSquad s;
for (int i=0;i<3;i++)
{
    char name[100];
    int tours;
    int members;
    cin>>name;
    cin>>tours;
    cin>>members;       
    squads[i] = MSquad(name, tours, members);

}

s = squads[0] + squads[1];
cout<<s;

mostMembers(squads, 3);

return 0;
}

The problem is that you're not understanding what operator + is supposed to return.问题是您不了解operator +应该返回什么。 According to your assignment:根据你的任务:

•operator + for adding two squads that will return as a result a new squad with number of members that is sum of the number of members of both squads, •operator + 用于添加两个小队,结果将返回一个新小队,其成员数量是两个小队成员数量的总和,

In your code, you're returning a MSquad& for operator + .在您的代码中,您为operator +返回了MSquad& This is not correct, as you should be returning a new MSquad object that is made up of the current object and the passed-in object.这是不正确的,因为您应该返回一个由当前对象和传入对象组成的新MSquad对象。

However, all is not lost, and we can keep the code you have now.但是,一切都没有丢失,我们可以保留您现在拥有的代码。 What's saved us is that you've written a user-defined copy constructor and destructor, so we can apply an easy fix.拯救我们的是您已经编写了一个用户定义的复制构造函数和析构函数,因此我们可以应用一个简单的修复程序。

The way we can fix this is to do the following (this was not in your requirements, but let's use the code you do have now):我们可以解决此问题的方法是执行以下操作(这不在您的要求中,但让我们使用您现在拥有的代码):

MSquad &operator+=(const MSquad &right) const
{
    members = members + right.members;
    if(right.members > members){
        name = new char[strlen(right.name) + 1];
        strcpy(name, right.name);
        tours = right.tours;
        //members = members + right.members;
    }
    return *this;
}

MSquad operator+(const MSquad &right) const
{
   MSquad temp(*this); // create a temporary copy of the current object 
   return temp += right;  // use += above on passed-in object and return object.
}

We've taken your existing code, made it operator+= , and just created an operator + using this function.我们采用了您现有的代码,将其设置为operator+= ,并使用此函数创建了一个operator + So we killed two birds with one stone.所以我们用一块石头杀死了两只鸟。 We created an operator += , which is supposed to return a reference to the current object, and wrote operator + using operator += as a helper function.我们创建了一个operator += ,它应该返回对当前对象的引用,并使用operator +=作为辅助函数编写operator + operator += Also, note that we created the temporary of the current object by taking advantage of the copy constructor.另请注意,我们利用复制构造函数创建了当前对象的临时对象。

In general, when you overload the operators such as + it is a better practice to overload op= first, and call it from operator op .通常,当您重载+等运算符时,更好的做法是先重载op= ,然后从运算符op调用它。


Please note that there are many other issues with your code involving mismanagement of pointers and memory leaks.请注意,您的代码还有许多其他问题,涉及指针管理不善和内存泄漏。 For example, the operator + function (now operator += in the answer) has a memory leak in that you didn't delete [] the previous name allocation.例如, operator +函数(现在答案中的operator += )存在内存泄漏,因为您没有delete []之前的name分配。 However I leave it up to you to fix these issues.但是,我让您来解决这些问题。

Did you try going thru with the debugger?您是否尝试过使用调试器?

Or, better yet - solve your problem on paper - then translate it into the code.或者,更好 - 在纸上解决您的问题 - 然后将其转换为代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM