在矩形类中超载运算符

Overloading operators in a Rectangle Class

本文关键字:超载 运算符 中超      更新时间:2023-10-16

我的程序将无法运行,并给我错误消息。首先,我忘了在标题文件中放置一个 }之后的分号。我回去添加了一个,但是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; 

这是学生9 *******。请忽略此消息,因为这是我遇到此帖子的任何教师。建议我这样做以避免任何类型的窃问题。

您有两个问题。首先是您没有声明或定义插入操作员。您在这里使用它:

cout << r3;

cout << r4;

您的第二个问题似乎是您尝试减去两个矩形的行具有一个不是负符号的字符:

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

添加插入运算符过载并修复了负符号后,您的代码编译了。

确保将fstream添加到标题中,也将所有标题添加到顶部,并在输出操作员的情况下超载。我希望这对您有帮助。