-6

Newly I've begun learning OOP.I've written simple program.But function int sum() has errors.Can you write decision of the problem.And explain errors.

class Int 
{
private:
   int num;
public
Int()
{
    num = 0;
}
Int(int n)
{
    num = n;
}
 int getValue()
{
    return num;
}
 int sum(const Int& n)
{
    return num+ n.getValue();
}
void main()
{
short a, b;
cout <<  "Enter 2 numbers:";
cin >> a >> b;
Int A(a), B(b), res;
cout << A.getValue() << " + " << B.getValue() << " = " << A.sum(B) <<"\n\n";
}
Sneikof
  • 13
  • 4
  • 1
    It looks like part of your source code was lost when posting. Please edit your post to include the entire source code. – Paul Belanger May 02 '18 at 17:14
  • Welcome to Stack Overflow! Generally, you should include the detailled error message that you get. In this case it looks like the body of your function `sum(const Int& n)` is missing – werner May 02 '18 at 17:14
  • 1
    If that is your real code you should get a *lot* of errors when building. – Some programmer dude May 02 '18 at 17:15
  • I'm sorry.Don't see – Sneikof May 02 '18 at 17:17
  • Take a close look at the code you show us. Especially the `sum` function. What are you doing in the `sum` function? – Some programmer dude May 02 '18 at 17:18
  • Please post the error you don't understand. Different compilers provide different errors, so we can not guess what error message you are asking us to explain. – Drew Dormann May 02 '18 at 17:22
  • 2
    Okay, your edit makes it a little better, but it still seems you are just dabbling around without much actual knowledge. Where do the `Int` class end? Perhaps you should take a few steps back, [get a couple of good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) and start over? – Some programmer dude May 02 '18 at 17:24
  • `int sum(const Int& n) const` - it fixes the main issue. I offer to fix other syntax issues yourself. – 273K May 02 '18 at 17:25

2 Answers2

0

You cannot declare a function inside another function like that. You have main() inside sum().

LawfulGood
  • 177
  • 5
0

Below is my attempt. There were some formatting issues but the trickiest problem was that getValue() is a const function.

class Int {
 private:
  int num;

 public:
  Int() { num = 0; }
  Int(int n) { num = n; }

  // getValue is a const function as it does not alter object 'n'.
  int getValue() const { return num; }
  int sum(const Int& n) { 
    int ret = num + n.getValue(); 
    return ret;
  }
};

int main() {
    int a, b;
    std::cout << "Enter 2 numbers:";
    std::cin >> a >> b;
    Int A(a), B(b), res;
    std::cout << A.getValue() << " + " << B.getValue() << " = " << A.sum(B) << "\n\n";
}
Peter
  • 98
  • 6