Search code examples
c++functionclassheadermember

Can't put class with main function?


Something I am working on is making a code that focuses on making a class that reverses an order of numbers. This will then get put into the main code that will eliminate any trailing zeroes. I can't seem to wrap my head around how classes work and where I am going wrong. Here is my code:

Numbers.h

#pragma once
#include <iostream>
class Numbers
{
public:
int digit
private:
void Numbers::reverse();
};

Numbers.cpp

#include "Numbers.h
#include <iostream>

using namespace std;

void Numbers::reverse(){
int n, reversedNumber = 0, remainder;

cout << "Enter the number you would like to manipulate!   " << endl;
cin >> n;

while (n !=0)
{
remainder = n % 10;
reversedNumber = reversed Number * 10 + remainder;
n /= 10;
}
//return *this;
}

Main.cpp

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
#include "Numbers.h"

using namespace std;

int main()
{
Numbers.reverse;

system("pause");
return 0;
}

I can't seem to make the reverse function in my Numbers.cpp work in the main function. I am new to C++ and am not sure where I am going wrong. Any help would be appreciated!


Solution

  • OK, there are a lot of mistakes or learning errors in your code. Your header file should look something like:

    #pragma once
    
    class Numbers
    {
    public:
      Numbers();
      ~Numbers();
    
      int Reverse(int input);  // Function is 'public'.
    };
    

    Your CPP file will then be (parts taken from S.O. post here):

    #include "Numbers.h"
    
    Numbers::Numbers()
    {
    }
    
    Numbers::~Numbers()
    {
    }
    
    // No need to store the value in 'digit' since this
    // is just an algorithm which can return the result.
    int Numbers::Reverse(int input)
    {
      int ret = 0;
    
      while(input > 0)
      {
        ret = ret * 10 + (input % 10);
        input = input / 10;
      }
    
      return ret; // Return the reversed number and let the user decide what to do.
    }
    

    Then you can use your class as follows:

    #include "Numbers.h"
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      int num;
    
      cout << "Enter a number to reverse: ";
      cin >> num;
    
      Numbers numClass;
    
      cout << "Reversed number is: " << numClass.Reverse(num) << endl;
    
      return 0;
    }