nyyp
nyyp

Reputation: 17

C++: cin, cout, etc. "does not name a type"

having a problem with the following piece of code:

#include <iostream>
using namespace std;

class Calculator
{
  public:

  int Sum(int first, int second);
};

int Calculator::Sum(int first, int second)
{
  int sum = first + second;
  return sum;
}

class Printer{
public:
  void Print();
  int first, second, calculated_sum;

  cout << "Give a first integer: ";
  cin >> first;
  cout << "Give a second integer: ";
  cin >> second;

  Calculator calc;
  calc.Sum(first, second);
};

void Printer::Print(){
  cout << "Sum: " << sum << endl;
}

int main()
{
  Printer object;
  object.Print();
}

I can only touch Printer class, as the others are not created by me.

The errors I get when I try to compile this:

code.cpp:22: error: ISO C++ forbids declaration of 'cout' with no type

code.cpp:22: error: expected ';' before '<<' token

code.cpp:23: error: ISO C++ forbids declaration of 'cin' with no type

code.cpp:23: error: expected ';' before '>>' token

code.cpp:24: error: ISO C++ forbids declaration of 'cout' with no type

code.cpp:24: error: expected ';' before '<<' token

code.cpp:25: error: ISO C++ forbids declaration of 'cin' with no type

code.cpp:25: error: expected ';' before '>>' token

code.cpp:28: error: ISO C++ forbids declaration of 'calc' with no type

code.cpp:28: error: expected ';' before '.' token

code.cpp: In member function 'void Printer::Print()':

code.cpp:32: error: 'sum' was not declared in this scope

So lot's of errors for so few lines of code. Any ideas on what to try to fix this?

Upvotes: 1

Views: 1211

Answers (1)

satsuma
satsuma

Reputation: 60

Basically what people are saying in the comments. You need to move

cout << "Give a first integer: ";
cin >> first;
cout << "Give a second integer: ";
cin >> second;

from sitting inside your class into some function. The area inside a class declaration is for declaring member variables and methods.

Same goes for the lines

Calculator calc;
calc.Sum(first, second);

The print method of the Printer object, for example, seems like a good place to put these lines.

Then you just need to make sure you declare sum in the scope of the print method and you should be good to go.

Upvotes: 3

Related Questions