Search code examples
c++undefinedsymbols

C++ Undefined Symbol Error


I am Getting undefined symbol error for all the integer and char values.Please Help me. The int x y and z are not working and also the char value of function.

#include <iostream.h>
#include <conio.h>
#include <math.h>
#include <string.h>

class Calculator
{
    public:
    int x;
    int y;
    int z;
    char function;

    void Calculate()
    {
      if(function=='+')
      {z=x+y;}
      else if(function=='-')
      {z=x-y;}
      else if(function=='*')
      {z=x*y;}
      else if(function=='/')
      {z=x/y;}
      else
      {cout<<"Wrong Function!!!";}
    }
};

void main()
{
    clrscr();
    Calculator  working;
    cout<<"Welcome!"<<endl;
    cout<<"Enter your first number:"<<endl;
    cin>>x;
    cout<<"Enter your function:"<<endl;
    cin>>function;
    cout<<"Enter your second number:"<<endl;
    cin>>y;
    working.Calculate();
    cout<<"Your Result is:"<<z<<endl;
    getch();
}

Solution

  • You need to pass the values to the function Calculate. Variables x, y, z and function are not accessible outside the class and also u need a return type to the function so that you can get the output from the function Calculate.

    class Calculator
    {
    public:
    int x;
    int y;
    int z;
    char function;
    
    int Calculate(int main_x,int main_y,char main_function)
    {
        x= main_x;
        y=main_y;
        function = main_function;
      if(function=='+')
      {z=x+y; return z;}
      else if(function=='-')
      {z=x-y; return z;}
      else if(function=='*')
      {z=x*y; return z;}
      else if(function=='/')
      {z=x/y; return z;}
      else
      {cout<<"Wrong Function!!!"; return 0;}
    }
     };
    
    void main()
     {
         clrscr();
       int main_x,main_y,main_z;
        char main_function;
    
    Calculator  working;
    cout<<"Welcome!"<<endl;
    cout<<"Enter your first number:"<<endl;
    cin>>main_x;
    cout<<"Enter your function:"<<endl;
    cin>>main_function;
    cout<<"Enter your second number:"<<endl;
    cin>>main_y;
    main_z = working.Calculate(main_x,main_y,main_function);
    cout<<"Your Result is:"<<main_z<<endl;
    getch();
    }