Hi! I'm having trouble getting my PowerN function to behave in the intended manner. I want to have a PowerN so that the constructor, with an inputted integer (N), would set the N value. Then, every time the PowerN object is called with a variable in the parameter, the value of the inputted variable will become N^x.
For instance:
int x,y
PowerN powerObject(3); // N is now 3
powerObject(x); // x is now 3^0 = 1
powerObject(x); // x is now 3^1 = 3
powerObject(y); // y is now 3^2 = 9
My current code runs, but fails the tests. I can't figure out how to increment the i value in order to change the input variables.
#include <iostream>
#include <vector>
#include <cmath>
usingnamespace std;
class PowerN{
public:
PowerN(); // Default constructor
PowerN(int);
voidoperator()(int& x);
private:
int N;
staticint i;
};
PowerN::PowerN(){} // Called when the constructor is called alone
PowerN::PowerN(int i){ // Called when the constructor is called with an integer variable
int N = i; // Takes in an integer and sets N to that value
}
int PowerN::i = 0;
void PowerN::operator()(int& x){ // Overloading the () operator since we're calling x several times.
i++; // Increments i every time an object of PowerN () is called
x = pow(N,i);
}
int main(){
//Testing the PowerN class
int test_power1, test_power2, test_power3;
PowerN power_three(3);
//test_power will now be 1
power_three(test_power1);
//test_power will now be 3
power_three(test_power2);
//test_power will now be 9
power_three(test_power3);
if (1 == test_power1) {
cout<<"PowerN works for 3^0!\n";
}
else {
cout<<"PowerN failed on 3^0!\n";
}
if (3 == test_power2 && 9 == test_power3) {
cout<<"PowerN works for 3^1 and 3^2!\n";
}
else {
cout<<"PowerN failed for 3^1 and 3^2!\n";
}
return 0;
}
Ah, whoops. I changed i++ so it came after line 3 and forgot to update. But when I did so, the first test would pass, but the second test would fail (the "3 == test_power2 && 9 == test_power3" test).
All you needed to to do was remove "int" from line 25. N = i;
With "int" you are declaring another variable named "N" which is local to the constructor and shadows masks the class member N. The local variable goes out of scope at the end of the ctor block and the class member "N" remains uninitialized.