Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I ran this code(which runs perfectly):
C++
#include <iostream>
using namespace std;
  
struct myint
{
private:
    int night;
public:
    myint() {}
    myint(int good) : night(good) {}
    
    myint operator+ (myint& input)
    {
        cout << night + input.night * 2;
        return 0;
    }
    
};
int main()
{
    myint hello(2);
    myint good(3);
    myint result = hello + good;
    return 0;
}

However, the problem i have is in the line where it says cout << night + input.night * 2. I dont know why i need to add the input.night and not just input. I want to know what the significance of the .night at the end is.

What I have tried:

i have tried searching for answers
Posted
Updated 4-Aug-21 0:08am
v2

1 solution

If you add night (i.e. this->) with input then ther is a type mismatch, because the former is a int while the latter is a myint.

That said, I would rewrite it this way
C++
#include <iostream>
using namespace std;

struct myint
{
private:
    int night;
public:
    myint(int good) : night(good) {}

    myint operator+ (const myint& input)
    {
      myint result(night + input.night * 2);
      return result;
    }
    int get() { return night;}
};

int main()
{
    myint hello(2);
    myint good(3);
    myint result = hello + good;
    cout << result.get() << endl;
}
 
Share this answer
 
v2
Comments
Greg Utas 4-Aug-21 7:43am    
5.
CPallini 4-Aug-21 7:52am    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900