H5W3
当前位置:H5W3 > 其他技术问题 > 正文

VS2019 C++ 重载‘+’,‘=’后不能正确的把相加后的表达式赋值给新创建的类。

图片说明
这个是重载的+
图片说明
这个是重载的=

图片说明
这个是主函数
图片说明
这里就是报错内容了

直接两个类相等都没问题,为什么进行重载后的+运算会出错呢?。。。

.cpp

#include "bds.h"
#include<iostream>
#include<iomanip>
using namespace std;
bds::bds(){
p = new char[80];
x1 = 0, x2 = 0,x3 = 0;
}
bds::~bds() {
delete[]p;
}
bds::bds(const char* x)
{
p = new char[80];
int t = 0;
for (; x[t] != ''; t++)
{
p[t] = x[t];
}
p[t] = '';
x1 = 0, x2 = 0, x3 = 0;
}
bds::bds(bds& c)
{
p = new char[80];
int i = 0;
for (; c.p[i] != ''; i++)
{
p[i] = c.p[i];
}
p[i] = '';
x1 = c.x1, x2 = c.x2, x3 = c.x3;
};
ostream& operator<<(ostream& out, bds& c)
{
out << c.p;
return out;
};//重载输出字符
istream& operator>>(istream& in, bds& c)
{
in >> c.p;
return in;
}
bds operator+(bds& s1, bds& s2)
{
bds s3;
s1.shu(), s2.shu();
s3.x1 = s1.x1 + s2.x1;
s3.x2 = s1.x2 + s2.x3;
s3.x3 = s1.x3 + s2.x3;
if (s3.x1!=0)
{
if (s3.x2!=0)
{
if (s3.x3!=0)
{
bds s("(0x+0x*x+0x*x*x)");
char c1[2],  c2[2], c3[2];
_itoa_s(s3.x1, c1, 10);
_itoa_s(s3.x2, c2, 10);
_itoa_s(s3.x3, c3, 10);
s3 = s;
s3.p[1] = c1[0];
s3.p[4] = c2[0];
s3.p[9] = c3[0];
}
}
}
return s3;
}
void bds::operator=(bds& c)
{
int i = 0;
for (; c.p[i] != ''; i++)
{
p[i] = c.p[i];
}
p[i] = '';
x1 = c.x1, x2 = c.x2, x3 = c.x3;
}
void bds::shu()
{
for (int i = 0; i<strlen(p); i++)
{
int k = 0;
if (p[i] == 'x')
{
int j = 0;
for (; p[i + j] != '+'; j++)
{
if (p[i + j] == '')
{
if (p[i + j - 1] == ')')
{
j = j - 1;
}
break;
}
}
k = j;
switch (j)
{
char str[100];
case 1: {str[0] = p[i - 1];
x1 = atoi(str);
if (p[i - 1] == '+')
{
x1 = 1;
}
}
break;
case 3: {str[0] = p[i - 1];
x2 = atoi(str);
if (p[i - 1] == '+')
{
x2 = 1;
}
}
break;
case 5: {str[0] = p[i - 1];
x3 = atoi(str);
if (p[i - 1] == '+')
{
x3 = 1;
}
}
default:
break;
}
}
i += k;
}
}
;

.h

#pragma once
#include<iostream>
#include<iomanip>
using namespace std;
class bds
{
private:
int x1,x2,x3;
char* p;
public:
bds();
~bds();
bds(const char* x);
bds(bds& c);
friend ostream& operator<<(ostream& out, bds& c);
friend istream& operator>>(istream& in, bds& c);
friend bds operator+(bds&s1,bds&s2);
void operator=(bds& c);
void show()
{
cout << x1 << "," << x2 << "," << x3;
}
void shu();
};

主程序

#include<iostream>
#include<iomanip>
#include"bds.h"
using namespace std;
int main()
{
bds t("(4x*x*x+3x*x+x)");
bds w("(2x+2x*x+2x*x*x)");
t.shu();
w.shu();
bds q;
q = t+w;
q = t;
q.shu();
//char s1[100]{ "(2x*x+1)" };
//cout << t << endl;
/*t.show();*/
q.show();
cout << q;
return 0;
}

回答

bds operator+(bds& s1, bds& s2) 改为bds operator+(const bds& s1, const bds& s2)
void operator=(bds& c) 改为void operator=(const bds& c);

本文地址:H5W3 » VS2019 C++ 重载‘+’,‘=’后不能正确的把相加后的表达式赋值给新创建的类。

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址