算术和关系运算符
Arithmetic and Relational Operators
我按照我的书到T,由于某种原因,当我试图运行我的程序,我得到完全错误的输出操作符-和操作符+我的输出。你知道我的重载操作符-和重载操作符+出了什么问题吗?程序编译得很好,但输出根本不对。
#include <iostream>
using namespace std;
class NumDays
{
private:
int ptrHours;
public:
NumDays(int H)// to set the pointer
{ setHours(H);}
void setHours(int H)
{ptrHours = H;}
int gethours() {return ptrHours;}
double calcDays()// function to calculate the days
{
double days;
days = ptrHours/8.0;
return days;
}
friend NumDays operator+(NumDays a, NumDays b);
friend NumDays operator-(NumDays a, NumDays b);
};
NumDays operator+(NumDays a, NumDays b)
{
return NumDays(a.ptrHours + b.ptrHours);
}
NumDays operator-(NumDays a, NumDays b)
{
return (a.ptrHours - b.ptrHours);
}
int main ()
{
NumDays first(0),
second(0),
third(0);
int hours1, hours2;
cout <<"Enter the how many hours you worked..." << endl;
cout <<"First set: ";
cin >> hours1;
while (hours1 < 0)
{
cout <<"nYou cannot enter a negative value. " << endl;;
cin >> hours1;
}
first.setHours(hours1);
cout <<"Second Set: ";
cin >> hours2;
while (hours1 < 0)
{
cout <<"nYou cannot enter a negative value. " << endl;;
cin >> hours2;
}
second.setHours(hours2);
cout <<"First set for days worked is " << first.calcDays() <<" days." << endl;
cout <<"Second set for days worked is " << second.calcDays() <<" days." << endl;
third = first - second;// where I try and do my arithmetic operators
cout <<"First - Second = " << cout << third.gethours() << endl;
third = first + second;
cout <<"First + Second = " << cout << third.gethours() << endl;
cin.ignore();
cin.get();
return 0;
}
问题出在你的代码中。
cout <<"First + Second = " << cout << third.gethours() << endl;
你不应该在cout中使用cout。你的print语句应该像这样
cout <<"First + Second = " << third.gethours() << endl;
希望这将帮助。谢谢你。
相关文章:
- 在 c++ 中对字符串进行操作的关系运算符无法按预期工作
- 为什么在C++中使用关系运算符创建的模板函数不能对字符串正常工作?
- 当关系运算符的含义相同时,为什么结果不同?
- C++使用关系运算符比较字符串
- 阐明关系运算符重载的概念(需要调试帮助)
- 迭代器关系运算符出错(带单独链接和迭代器的自定义哈希表)
- 当我有两个对象时<<如何重载运算符?(有关系)
- 为什么赋值运算符和相等运算符之间没有 1:1 的关系?
- 重载运算符<关系C++
- C++使用 shared_ptr 但调用了对象的关系运算符?
- C++ 字符 - 关系运算符
- 使用关系运算符比较指针意味着什么
- C++ 如何重载关系运算符以检查两个对象是否相同
- 枚举类的关系运算符重载
- C++ STL 关系运算符如何比较堆栈
- 为什么指针类型的内置关系运算符不生成C++的总顺序?
- ostream 插入运算符与其非成员重载之间的关系
- 字符串类关系运算符重载
- 与关系运算符的字符串比较(长度不同)
- 为两个类定义重载的强制转换运算符,这两个类之间具有循环依赖关系