在矩形类中超载运算符
Overloading operators in a Rectangle Class
我的程序将无法运行,并给我错误消息。首先,我忘了在标题文件中放置一个 }
之后的分号。我回去添加了一个,但是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添加到标题中,也将所有标题添加到顶部,并在输出操作员的情况下超载。我希望这对您有帮助。
相关文章:
- 虚拟超载运算符>>和<<
- 为什么我的超载"+"运算符返回的总额错误?
- 我可以防止与null与超载运算符==进行比较
- 超载 运算符添加const char
- 是否有一种方法可以在超载运算符函数中接触默认运算符函数
- 堆上的模板类超载运算符
- 我想将超载运算符添加到派生类中
- 超载 *运算符时无法转换错误
- 在将对象声明为挥发性时,如何在C 中超载运算符
- 超载运算符*与操作员双重模棱两可()
- 在C 中的超载运算符中使用局部变量
- 如何使用超载 运算符组合两个链接列表
- C 超载 运算符,因此您可以在该类中添加不同的类并获得第三类
- 超载运算符== C 时获取SigSeGV(分割故障)
- 超载运算符=在单链接列表中
- 超载 运算符在C 中加入两个字符串(一些疑问)
- 使用超载运算符添加构造函数
- 为什么在C 中调用模板超载运算符时,我会遇到细分故障
- 是否可以超载[]运算符在不定义类的情况下访问特定的字符
- 没有可行的超载运算符[]