Here I need to add two numbers, but my constructor has only one parameter. And it should be has one parameter. Using the addFunc I need to add my two different numbers.
int result = 0;
class Num{
private:
int a;
public:
Num(int a) {
a = a;
}
int getA(){
return a;
}
void setA(int a){
a = a;
}
int addFunc() {
return result += getA();
}
}
};
Here is my 'main' function and I need to output the sum of two numbers which is supposed to be saves to 'result' variable.
The problem is that instead of getting the real result 5+6=11 I get this ->
Expanding on Bob__'s suggestion it seems likely that your code is supposed to look something a bit like this
class Num {
private:
int a;
public:
Num(int a) {
this->a = a;
}
int getA() {
return a;
}
void setA(int a) {
this->a = a;
}
int addFunc(Num other) {
return a + other.a;
}
};
int main()
{
Num num(5);
Num num2(6);
cout << num.addFunc(num2);
}
As you can see, it's a bit more logical, a bit simpler, and doesn't need to use a global variable to add two numbers togther.
Related
You can redefine operator << in class by overload it.
However, how do you code it so that it would operates specific to a certain class member?
for example
class C
{
int a;
double b;
}
// I would like something like
void main ()
{
C c;
c.a << 1; // sets class member a to value 1;
}
I want a operator defined in Class C that operates specifically to class member a.
a pesudo-code would be
class C
{
int a;
double b;
void operator << (istream & fin)
{
... fin.get()... some code
}
}
Stating the obvious for a moment, assuming the variable is public, you'd use:
class C
{
int a;
double b;
}
// I would like something like
void main ()
{
C c;
c.a = 1; // sets class member a to value 1;
}
The << and >> operators are bit shifts, which have their own meaning. Overloading those for your own purpose is probably a bad idea.
The C++ way of doing things is to avoid setting member variables externally where possible (e.g. using RAII approaches, to set data at initialisation)....
class C
{
public:
C(int a, double b) : a(a), b(b) {}
int getA() const { return a; }
double getB() const { return b; }
private:
int a;
double b;
};
.... Or by adding a setter method if you really need it, e.g.
class C
{
public:
C(int a, double b) : a(a), b(b) {}
int getA() const { return a; }
double getB() const { return b; }
void setA(int v) { a = v; }
void setB(double v) { b = v; }
private:
int a;
double b;
};
You could in theory generate a new type, and overload the operators for that type, but it's not something I'd recommend (because changing the meaning of an operator is almost always a bad idea)
struct MyIntType {
int i;
// overload cast operator
operator int () {
return i;
}
// assign
MyIntType& operator = (const int& v) {
i = v;
return *this;
}
// not recommended :(
MyIntType& operator << (const int& v) {
i = v;
return *this;
}
};
class C
{
public:
MyIntType a;
double b;
};
void main ()
{
C c;
c.a << 1;
}
Having read your comment above, it sounds like you want to do this:
class C
{
public:
// I'm still not recommending this :(
C& operator << (const int& v) {
a = v;
return *this;
}
private:
int a;
double b;
};
void main ()
{
C c;
c << 1; //< now sets c.a
}
If I have a friend function can I somehow use set() to assign a value to a private variable inside the function? Or some other method?
Example : Here I have 3 private variables. I tried to make the sum of 2 of them and store the result in the 3rd one. I tried to do it with a setter but the result is 0. In main it works, but I don't know if I can make it work in the class function.
#include <iostream>
using namespace std;
class Function{
private:
int a;
int b;
int sum;
public:
Function() = default;
Function(int _a, int _b);
friend int sumNumber(Function f);
//Setter and getter
int getA() const;
void setA(int a);
int getB() const;
void setB(int b);
int getSum() const;
void setSum(int sum);
};
Function::Function(int _a, int _b) {
this->a = _a;
this->b = _b;
}
int Function::getA() const {
return a;
}
void Function::setA(int a) {
Function::a = a;
}
int Function::getB() const {
return b;
}
void Function::setB(int b) {
Function::b = b;
}
int Function::getSum() const {
return sum;
}
void Function::setSum(int sum) {
Function::sum = sum;
}
int sumNumber(Function f) {
int a = f.getA();
int b = f.getB();
int sum = a + b;
f.setSum(sum);
return sum;
};
int main() {
Function AA(1,2);
cout << sumNumber(AA);
cout << " " << AA.getSum();
AA.setSum(sumNumber(AA));
cout << "\n" << AA.getSum();
return 0;
}
Output :
3 0
3
As alluded to in the comments, the issue is with this function:
int sumNumber(Function f) {
int a = f.getA();
int b = f.getB();
int sum = a + b;
f.setSum(sum);
return sum;
};
Let us walk through your code:
Function AA(1,2);
You create a object of type Function, called AA and you allocate each member variable of that object via the constructor (1 and 2).
cout << sumNumber(AA);
You call your method (sumNumber) and pass to it a copy of your variable AA. That function adds the two numbers together and internally calls setSum.
cout << " " << AA.getSum();
You now try to display the sum value by calling the getSum method. But the issue was that you passed a copy of your variable into the sumNumber function. The original AA variable was left alone.
To fix this you need to adjust your function by adding an ampersand &. Like this:
int sumNumber(Function& f) {
int a = f.getA();
int b = f.getB();
int sum = a + b;
f.setSum(sum);
return sum;
};
Now your variable AA is being passed by reference and not by value. There are lots of tutorials about this concept.
I want to make a class/struct where one of the attributes is functionally dependent on other attributes. How can this be achieved?
struct Numbers {
int a;
int b;
int c; // c == a+b
}
Numbers n1 {1, 2, 3}; // Ok.
Numbers n2 {1, 2, 4}; // Error!
In my use case, a, b, c are constant, if that matters (so const int may be used).
All attributes will appear many times in class/struct methods, so the goal is to cache the value a+b. Addition is used as an example, the dependency function may be more complex.
If a and b are mutable then you can't enforce that c is kept in sync; all three would have to be const for you to enforce this invariant.
The simplest approach would be to make c a function:
struct Numbers {
int a;
int b;
int c() const { return a + b; }
}
If you want the value of c to be cached instead of computed when needed then you need to hide a and b behind accessors as well so that you can update c when they are updated.
class Numbers {
public:
Numbers(int a, int b) : ma{a}, mb{b} { updateC(); }
int a() const { return ma; }
int b() const { return mb; }
int c() const { return mc; }
void a(int v) { ma = v; updateC(); }
void b(int v) { mb = v; updateC(); }
// No setter for c
private:
void updateC() { mc = ma + mb; }
int ma;
int mb;
int mc;
};
You can do something like that:
struct Numbers {
Numbers(int a, int b) : a(a), b(b), c(a + b) {}
private:
int a;
int b;
int c; // c == a+b
};
Edit:
To keep the values of a and b updated, and to get the values of those variables, you'll have to use get & set methods, like in #cdhowie response.
I have a class MyClass and another class that holds an array of MyClass, as follows:
class MyClass {
int a;
float b;
void SetInt(int value)
{
a = value;
}
void SetFloat(float value)
{
b = value;
}
}
class MyClassArray {
std::vector<MyClass> classList;
}
What is the easier way to create a new MyClass, insert an object in MyClassArray and call the methods to store value on it ?
Can I just create a temporary MyClass and insert it on the vector, calling the function in one statement ? Like:
classList.push_back(MyClass().SetInt(21));
classList.push_back(MyClass().SetFloat(1.23));
Is that valid ?
BTW: I need in vector a one object MyClass with 21 set on a and another one with 1.23 set on b, that´s why I´m not using initializers for a and b.
you can use chaining :
class MyClass {
int a;
float b;
public:
MyClass& Set(int value) { a = value; return *this; }
MyClass& Set(float value) { b = value; return *this; }
};
this enables thing like:
MyClass a;
a.Set(1).Set(1.5f);
and also:
vector<MyClass> vec;
vec.push_back(MyClass{}.Set(3));
Use your constructor
class MyClass {
int a;
float b;
}
class MyClassArray {
std::vector<MyClass> classList;
classList.push_back(MyClass(21,1.23));
}
You can use constructors for this. If you overload the constructor to take either an int or a float you would be able to set the value for both of the situations that you outlined.
class MyClass
{
int a;
float b;
MyClass(int i) : a(i) { }
MyClass(float f) : b(f) { }
}
this way you could add objects to the vector by doing this:
std::vector<MyClass> classList;
classList.push_back(MyClass(21));
and by doing this:
classList.push_back(MyClass(1.23));
If you really need to call a separate method you could do it like this:
class MyClass {
int a;
float b;
MyClass& SetInt(int value)
{
a = value;
return *this;
}
MyClass& SetFloat(float value)
{
b = value;
return *this;
}
}
Which will return a reference to the class. It is far better to do it using constructors though.
class c {
private:
int n[10];
public:
c();
~c();
int operator()(int i) { return n[i];};
};
class cc {
private:
public:
c *mass;
cc();
~cc();
c& operator*() const {return *mass;};
};
int somfunc() {
c *c1 = new c();
cc * cc1 = new cc();
(*cc1->mass)(1);
delete c1;
}
I've got a pointer into class cc to class c.
Is there any way to get rid of record like this:
(*cc1->mass)(1);
and write somethink like that:
cc1->mass(1);
is it impossible?
When I saw the tags "c++" and "operator overloading", my mind alarm turns ON.
C++ operator overloading is complex, and some operators like "()" or "->" make it more difficult.
I suggest, before overloading operators, making either a global function or method with the same purpouse, test it works, and later replace it with the operator.
Global friend function example:
class c {
private:
int n[10];
public:
c();
~c();
// int operator()(int i) { return n[i]; }
// there is a friend global function, that when receives a "c" object,
// as a parameter, or declares a "c" object, as a local variable,
// this function, will have access to the "public" members of "c" objects,
// the "thisref" will be removed, when turned into a method
friend int c_subscript(c thisref, int i) ;
};
int c_subscript(c* thisref, int i)
{
return c->n[i];
}
int main()
{
c* objC() = new c();
// do something with "objcC"
int x = c_subscript(objC, 3);
// do something with "x"
return 0;
} // int main(...)
Local function ( "method" ) example:
class c {
private:
int n[10];
public:
c();
~c();
// int operator()(int i) { return n[i]; }
int subscript(int i) ;
};
int c::subscript(int i)
{
return this.n[i];
}
int main()
{
c* objC() = new c();
// do something with "objcC"
int x = c->subscript(objC, 3);
// do something with "x"
return 0;
} // int main(...)
And, finally use the overloaded operator:
class c {
private:
int n[10];
public:
c();
~c();
int subscript(int i) ;
int operator()(int i) { return this.subscript(i); }
};
int c::subscript(int i)
{
return this.n[i];
}
int main()
{
c* objC() = new c();
// do something with "objcC"
int x = c->subscript(3);
// do something with "x"
int x = c(3);
// do something with "x"
return 0;
} // int main(...)
Note that in the final example, I keep the method with a unique identifier.
Cheers.
Could always do this:
class cc {
private:
c *_mass;
public:
c& mass() const {return *_mass;};
};
Now..
cc1->mass()(1);
If mass were an object, not a pointer, you could use the syntax you want:
class cc {
private:
public:
c mass;
cc();
~cc();
const c& operator*() const {return mass;};
};
…
cc1->mass(1);
You can with
(*(*cc1))(1)
because operator() is applied to an object, not a pointer.
You can use
(**cc1)(1);
Or
cc1->mass->operator()(1);