What does this function do [duplicate] - c++

In the .h file given to me by my professor, he's written
double operator()(double x) const;
The point of the overload is to read in x as a double and use it to evaluate a polynomial that's stored in the class object Term. What I've come up with in the class implementation is
double operator()(double x) const
{ double result = 0.0;
for (int i = 0; i < getSize(); i++)
result += (getCoeff(i) * pow(x, getExponent(i)));
return result;
}
How do I call it from the application? I've tried different calls like
Polynomial p;
p.operator(x);
or
Polynomial::operator(x);
or
operator(x);
but always get errors when compiling.

The usual form is to call it as if your instance was a function:
double x = 3.1416;
Polynomial p;
double y = p(x);
Alternatively, you can explicitly call the operator:
double x = 3.1416;
Polynomial p;
double y = p.operator()(x);
Here's a simplified example:
#include <iostream>
struct Foo
{
double operator()(double x) const { return x*2; }
};
int main()
{
Foo f;
std::cout << f(2.5) << std::endl;
}

Related

Problem with a class setter function. Class setter function does not assign values properly

the statement below the function calling is not executed. i am at a loss, why this is so? could someone please clarify. Please consider the code below :
#include<iostream>
#include<cmath>
using namespace std;
class Matrix
{
private:
int row,col;
double *values;
public:
Matrix();
Matrix(int r, int c, double* x);
void setdim(int m, int n){row=m;col=n;}
int getrowdim() const {return row;}
int getcoldim() const {return col;}
void set_values(int i, double x);
double get_value(int i) const;
friend Matrix operator+(const Matrix &A, const Matrix &B);
};
Matrix::Matrix()
{
this->row = 0;
this->col = 0;
this->values = NULL;
}
Matrix::Matrix(int r, int c, double* x)
{
this->row = r;
this->col = c;
this->values = new double[r*c];
for (int i =0;i<r*c;i++)
{
cout<<"Enter value ["<<i<<"] ";
cin>>this->values[i];
}
}
void Matrix::set_values(int k, double x)
{
this->values[k] = x;
}
Matrix operator+(const Matrix &A, const Matrix &B)
{
int rowa = A.getrowdim();
int cola = A.getcoldim();
int rowb = B.getrowdim();
int colb = B.getcoldim();
if(rowa == rowb && cola == colb)
{
Matrix C;
C.setdim(rowa, colb);
for(int i =0; i< rowa*cola ; i++)
{
cout<<"i = "<<i<<", A.get_value = "<<A.get_value(i)<<", B.get_value = "<<B.get_value(i)<<endl;
double m = A.get_value(i) + B.get_value(i);
cout<<m<<endl;
C.set_values(i, m );
cout<<"Returned from C.set_values()"<<endl;
// THIS STATEMENT DOES NOT GET PRINTED. PLEASE TELL THE REASON // WHY. I SUSPECT THE ERROR IS HERE
}
return C;
}
else
{
cout<<"Invalid Operation";
return A;
}
}
double Matrix::get_value(int i) const
{
return this->values[i];
}
int main()
{
Matrix A(2,2,NULL);
Matrix B(2,2,NULL);
Matrix C;
C = A+B;
return 0;
}
The statement - Returned from C.set_values() does not get printed at all .
Could someone help clarify why this is the case? Thanks a lot for the help!
Here:
Matrix C; // (1)
C.setdim(rowa, colb); // (2)
for(int i =0; i< rowa*cola ; i++)
{
cout<<"i = "<<i<<", A.get_value = "<<A.get_value(i)<<", B.get_value = "<<B.get_value(i)<<endl;
double m = A.get_value(i) + B.get_value(i);
cout<<m<<endl;
C.set_values(i, m ); // (3)
You default construct a Matrix (1). The default constructor just sets the member values to NULL. Then you adjust the size members in (2), but values is still NULL. Then, in (3) you call set_values which tries to access array elements, but there is no array.
The problem is that your Matrix has a raw owning pointer as member. When a class manages a resource you must follow the rule of 3/5. If you don't, the class is broken. Managing a resource is not trivial, and following the rule of 3/5 is just the bare minimum.
The simpler alternative that you should strive for is the rule of 0. For a class that does not manage a resource, the compiler generated special members are just right. If you replace the raw pointer member with a std::vector<double> then you do not need to worry about copying, assignment or destruction, because the compiler will generate the required methods for you.

C++ ints getting corrupted, generated with rand()

I'm attempting to write a C++ program that uses a Point class consisting of x and y coordinates (ints) and a boolean. The x and y coordinates should be in the range from 0-100, but upon execution and with a print statement to test, the values printed out are corrupted.
My code looks like this:
int main(int argc, const char * argv[]) {
vector<Point> points;
for (int i = 0; i<200; i++) {
int rand_X = (rand() % 100) + 1;
int rand_Y = (rand() & 100) + 1;
Point point = Point(rand_X, rand_Y, false);
cout<< point.getX() << " " << point.getY() << endl;
points.push_back(point);
}
return 0;
and the Point class looks like this, if that's relevant:
struct Point {
public:
int x;
int y;
bool in_layer;
Point(int x, int y, bool in_layer) {}
int getX() {return this->x;}
int getY() {return this->y;}
};
And the output is just "-272632592 32766" repeated 200 times, which I'm assuming is a corrupted value.
Any ideas what could be causing the issue?
Your constructor didn't do anything, which contribute to an UB when you call getX getY methods. Plus, I think there's no need to use constructor and getx gety methods here.
If that's a code for learning, you may need to assign to the member x, y in the constructor or use the folowing technique (initialization list):
Point(int _x, int _y, bool _in_layer) : x(_x), y(_y), in_layer(_in_layer){}

Change local variable in a function from main scope without using global variables

I have a function in my code of the type:
double f (double x, double y){
...
int entry_1 = 0;
int entry_2 = 1;
...
}
The values for entry_1 and entry_2 will change after some loops inside the function f. The function f will be used in the same way in the main script:
double f_value;
double y_instance = 0.5;
for (int i = 0; i<100; i++){
...
f_value = f(x*i, y_instance);
...
}
Let's suppose that after this loop, entry_1 = 7 and entry_2 = 0, because they changed inside the f function.
If entry_1 and entry_2 were global variables, now I would do something like this:
entry_1 = 0;
entry_2 = 1;
for (int i = 0; i<100; i++){
...
f_value = f(x*i-2, y_instance);
...
}
I don't think is a good idea to set entry_1 and entry_2 as input parameters, because I would be forced to pass some value during the for loops in the main function. I want that entry_1 and entry_2 are manipulated by f during the for loops, and after those loops, reinitialize them from the main function.
You could use a class, and make your program object-oriented:
class Foo
{
public:
double f (double x, double y)
{
return x + y + entry_1; // for example.
}
void setEntry1(double value)
{
entry_1 = value;
}
private:
double entry_1 = 0;
double entry_2 = 1;
};
You then use it like that:
Foo object;
object.setEntry1(0.5);
double z = object.f(0.1, 0.2);
double z1 = object.f(0.2, 0.3);
That allows you to have multiple object performing f with different entry values. And to change those entry values.
You can turn them into parameters of the function.
But instead of by copy, take them by reference :
double f (double& entry_1, double& entry_2, double x, double y)
{ ...... }
That way they can be stored wherever You want, but will retain the modifications between calls of the function.
But a better way would be for it to be private variables of a class.

Confusion over Initializing variables and changing them in C++

I'm trying to make a program that will allow the user to enter in a heighth and width of a rectangle, and display the area, however every step of my program is done using functions as part of the assignment.
The issue I'm having is that I have the variables assigned and intialized, though I'm not sure how to overwrite them with user inputted data. If I don't initialize the variables at all the program will not run. I was hoping someone could tell me what I'm doing wrong. My code is:
#include <iostream>
using namespace std;
double getWidth(int x);
double getLength(int y);
double getArea(double x, double y, double a);
double displayData(double a);
int main()
{
int x = 0, y = 0, a = 0;
getWidth(x);
getLength(y);
getArea(x, y, a);
displayData(a);
system("pause");
return 0;
}
double getWidth(int x)
{
cout << "Please enter the width: ";
cin >> x;
return x;
}
double getLength(int y)
{
cout << "Please enter the length: ";
cin >> y;
return y;
}
double getArea(double x, double y, double a)
{
a = x*y;
return a;
}
double displayData(double a)
{
cout << a << endl;
return a;
}
There are two ways of passing variables. Method number one is to pass by value. This is the most common method, and it is the one your program is doing. In this method, a copy of the data in the variable is being made and supplied to the function. Your function only changes the copy and not the original variable.
The second method is to pass by reference. When passing by reference, your function effectively has a pointer to the original variable and can thus change it. To pass by reference, put in an ampersand (&) in front of the variable in the function header. Note in the code below that it is not necessary to pass x and y to getArea by reference because getArea only needs to read these variables not write to them.
This however will introduce a new problem for you. When you pass by value it is possible to change the variable type to a larger type without an explicit cast. This is not possible with passing by reference because the different parts of the program would then be trying to treat the variable as a different type. i.e. main wants to write to/read from a as if it is an integer and getArea wants to write to/read from a as if it is a double. These two data types have different sizes and and different formats so this is not possible. Thus you have to declare a is a double in main.
#include <iostream>
using namespace std;
double getWidth(int &x);
double getLength(int &y);
double getArea(double x, double y, double &a);
double displayData(double a);
int main()
{
int x = 0, y = 0;
double a;
getWidth(x);
getLength(y);
getArea(x, y, a);
displayData(a);
system("pause");
return 0;
}
double getWidth(int &x)
{
cout << "Please enter the width: ";
cin >> x;
return x;
}
double getLength(int &y)
{
cout << "Please enter the length: ";
cin >> y;
return y;
}
double getArea(double x, double y, double &a)
{
a = x*y;
return a;
}
double displayData(double a)
{
cout << a << endl;
return a;
}
You seem to be confusing a few different concepts. You should either be passing references and assigning them within the functions, or passing less values and assigning them to some variable in main. For example, your getWidth should be:
double getWidth() {
double w;
cin >> w;
return w;
}
and in your main you should have:
int main() {
/* ... */
double width = getWidth();
/* ... */
}
And so on for the others as well. You should be looking into references and pointers in C++ as well, that would be the other way that you could do this (and you are seemingly confused about). Finally you should definitely find an introduction to functions in some intro to C++ book, as someone said above.

Rotating Function C++

Im trying to rotate a set of values of template class
these are the instructions
Implement a function to rotate values forward among 3 variables. Rotations greater than 3 wrap around. This function must support multiple types and uses the following prototype:
template <class T>
void rotate (T & a, T & b, T & c, int r);
#include <iostream>
#include <string>
using std::string;
using std::endl;
using std::cin;
using std::cout;
template <class T>
void rotate (T & a, T & b, T & c);
int main ()
{
int x = 1;
int y = 2;
int z = 3;
cout << rotate(x, y, z) << endl;
return 0;
}
template <class T>
void rotate (T&a, T&b, T&c)
{
T & d = b;
while (a != d)
{
swap(&a++, &d++);
if (d == c)
d = b;
else if (a == b)
b == d;
}
}
If I guessd right what you want is the values to rotate among a, b, c. In your original funcion you have int r but in your final implementation r is missing. First of all take the r%3 and rotate by that amount. The rotate is pretty simple you had the initial idea just need to flesh it out properly.
Your best best would be to use a for loop like this:
template <class T>
void rotate(T &a, T &b, T&c, int r)
{
T temp = 0;
for (int i = 0; i < r; i++)
{
temp = c;
c = b;
b = a;
a = temp;
}
}
Then the call in the main function would be:
rotate(x, y, z, 4); //4 is the number of rotations