gpt4 book ai didi

c++ - 在 Rectangle 类中重载运算符

转载 作者:行者123 更新时间:2023-11-30 05:43:30 26 4
gpt4 key购买 nike

我的程序无法运行并给我错误消息。起初,我忘了在头文件中的 后面放一个分号。我返回并添加了一个,但 Visual Studio 一直给我错误。

错误消息链接:https://pastebin.com/wSEnedMY

#ifndef RECTANGLE_H
#define RECTANGLE_H
using namespace std;

// Class declaration
class Rectangle
{
private:
double length;
double width;
public:
Rectangle();
Rectangle(double, double);
Rectangle operator-(Rectangle &);
Rectangle operator*(Rectangle &);
friend istream& operator>>(istream &, Rectangle &);
};
#endif

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

// Default Constructor
Rectangle::Rectangle()
{
length = 0;
width = 0;
}

// Constructor
Rectangle::Rectangle(double len, double wid)
{
length = len;
width = wid;
}

// Overload the - operator
Rectangle Rectangle::operator-(Rectangle &otherRect)
{
Rectangle temp;

temp.length = this->length - otherRect.length;
temp.width = this->width - otherRect.width;

return temp;
}

// Overload the * operator
Rectangle Rectangle::operator*(Rectangle &otherRect)
{
Rectangle temp;

temp.length = this->length * otherRect.length;
temp.width = this->width * otherRect.width;

return temp;
}

// Overload the cin operator
istream& operator>>(istream &is, Rectangle& r)
{
// Prompt user for length
cout << "Enter the length: ";
is >> r.length;

// Prompt user for width
cout << "Enter the width: ";
is >> r.width;

return is;
}

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

int main()
{
Rectangle r1(3,5);
Rectangle r3, r4, r5, r6;
Rectangle r2(r1); // Copy constructor

cin >> r2; // Read in value for r2 and to be overloaded

r3 = r1 – r2;
cout << r3;

r4 = r1 * r2;
cout << r4;

system("PAUSE");

return 0;

This is student 9*********. Please ignore this message as this is for any of my instructors who come across this post. I have been advised to do this to avoid any type of plagiarism issues.

最佳答案

你有两个问题。首先是您没有声明或定义插入运算符。你在这里使用它:

cout << r3;

cout << r4;

你的第二个问题似乎是你试图减去两个矩形的那条线有一个不是减号的字符:

r3 = r1 – r2
// ^This isn't a subtraction, it's a hyphen or something.

r3 = r1 - r2
// ^See the difference?

添加插入运算符重载并修复减号后,您的代码已编译。

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

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