[英]Realize "-" operator overloading as a friend function of class
I try to realize difference of sets with "-".我试图用“-”来实现集合的差异。 For example:
例如:
Set a = 1 2 3 4;
Set b = 3 4 5 6;
Set c = a - b; // (1 2);
How i should overload operator?我应该如何重载运算符? I tried to use frienldy function, but it can't work with variable "size".
我尝试使用 frienldy 函数,但它不能使用变量“大小”。 Visual Studio show error "c2597" at 28th line (size++;) I can't understand, how to overloading "-" for using it with two sets.
Visual Studio 在第 28 行(大小++;)显示错误“c2597”,我无法理解,如何重载“-”以将其与两组一起使用。 When I overload method of class, i can use only one argument.
当我重载类的方法时,我只能使用一个参数。 When i use friend-function, i can use twi arguments (Set a, Set b), but i can't work with variable "size".
当我使用友元函数时,我可以使用 twi 参数(设置 a,设置 b),但我不能使用变量“大小”。
#include <iostream>
#include <locale.h>
#include <conio.h>
#include <vector>
using namespace std;
class Set {
private:
int size;
vector <int> vect;
public:
Set() { size = 0; }
~Set() { vect.clear(); }
void Enter();
void Show();
friend Set operator-(Set a, Set b)
{
size = 0;
vect.clear();
int i, j, n = 0;
for (i = 0; i < a.size; i++) {
int cnt = 0;
for (j = 0; j < b.size; j++)
{
if (a.vect[i] == b.vect[j]) cnt++;
}
if (cnt == 0) {
size++;
vect.push_back(a.vect[i]);
}
}
return a;
}
void add()
{
int element;
cout << "Введите новый элемент " << endl;
cin >> element;
size = size + 1;
vect.push_back(element);
}
};
void Set::Enter() {
cout << "Введите размер " << endl;
cin >> size;
vect.resize(size);
cout << "Введите элементы :" << endl;
for (int i = 0; i < size; i++)
{
cin >> vect[i];
}
}
void Set::Show() {
cout << "Множество: " << endl;
for (int i = 0; i < size; i++)
cout << vect[i] << " ";
cout << endl;
}
int main() {
setlocale(LC_ALL, "RUS");
Set a;
a.Enter();
Set b;
b.Enter();
Set c;
c = a - b;
c.Show();
c.add();
c.Show();
_getch();
return 0;
}
UPD: I made it through method: UPD:我通过方法做到了:
Set operator-(const Set& b)
{
Set a = *this;
Set tmp;
tmp.size = 0;
vect.clear();
int i, j, n = 0;
for (i = 0; i < a.size; i++) {
int cnt = 0;
for (j = 0; j < b.size; j++)
{
if (a.vect[i] == b.vect[j]) cnt++;
}
if (cnt == 0) {
tmp.size++;
tmp.vect.push_back(a.vect[i]);
}
}
return tmp;
}
friend
functions are not member methods, so you have to remove/replace usage of (implicit) this
as size = 0
, you might add extra object: friend
函数不是成员方法,因此您必须删除/替换(隐式) this
作为size = 0
用法,您可能会添加额外的对象:
friend Set operator-(Set a, Set b)
{
Set res;
for (int i = 0; i < a.size; i++) {
int cnt = 0;
for (int j = 0; j < b.size; j++)
{
if (a.vect[i] == b.vect[j]) cnt++;
}
if (cnt == 0) {
res.size++;
res.vect.push_back(a.vect[i]);
}
}
return res;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.