How to define the operator= in a class to make a variable in it to be assigned to an outside variable - operator-overloading

I have example code and classs:
class a{
int x;
a(){
this->x = 335; /* example number*/
}
public:
void operator=(int);
};
void a::operator=(int source){
this->x = source;
}
main(){
int i = 100;
a example_class;
example_class = i; //works fine!
i = example_class; /*this is what I want to do.*/
}
the problem with this hole thing is that I can't
make the operator= be a friend function
therefore the command: "i = example_class"
can't be done because I can't create a function in //the the int class like I normally would with my own classes.
Finally:
How can I complete the command:
"i = example_class" when the
operator= can't have more than 1
parameter?
notes:
I know the code doesn't do anything.
And is only an example. The point
Is what actually matters.
Also, I need to make it clear that I
cannot create any functions in the
Target class(in this case int). Only in
the source class(in this case a).
I also want to make clear that I know
that it's impossible to declare the
operator= as a friend function.
I know that I could just create a function
to get a reference to int x or make
int x public but I didn't want to do that
because the real code involves complex
functions for converting between types
so it's vary important to me to be able
to write: "i = example_class;".
Thanks,
Ronen.

Working example.
#include <iostream>
class a {
int x = 355;
public:
void operator=(int);
operator int();
};
void a::operator=(int source){
x = source;
}
a::operator int() {
return x;
}
int main(int, char**) {
int i = 100;
a example_class;
example_class = i;
int j = example_class;
std::cout << j << std::endl;
}

Related

Why does vscode tell constructor defined outside class is inaccesible?

I have defined a constructor and then tried initializing an object but vscode tells me that the constructor is inaccessible. I don't understand what the problem is
this is my code
using namespace std;
#include<iostream>
class player{
// attributes
int xp{0};
string name;
int health{0};
float avg_score{0};
int tot{0};
int c{0};
// methods
void add_score(int score){
tot += score;
c++;
};
void display_avg_score(){
avg_score = tot/c;
cout << avg_score << endl;
};
void player_is_perfect(){
if((xp > 5) && (avg_score > 23)){
cout << "Perfect"<< endl;
}
};
// defining a constructor
player(int exp,float avg);
};
player::player(int exp,float avg){
xp = exp;
avg_score = avg;
};
int main(){
player frank{23,45.6};
};
As Raymond specified, classes have default access specifier "private". Anything you want to access outside the class should be preceded by the "public" statement like so
class player{
// attributes
int xp{0};
string name;
int health{0};
float avg_score{0};
int tot{0};
int c{0};
public:
// methods
void add_score(int score){
tot += score;
c++;
}
// rest of class
};

Binary Operator overloading for a member enum class (with non static members)

The following code doesn't compile.
error: invalid use of non-static data member 'data'
#include <iostream>
#include <unordered_map>
#include <vector>
class Domain {
public:
enum class fieldname { x_, y_ };
std::unordered_map<fieldname, std::vector<double>> data;
// default constructor. Hard coding is only for this test!
Domain() {
data[Domain::fieldname::x_] = std::vector<double>{1, 23, 4};
data[Domain::fieldname::y_] = std::vector<double>{1, 23, 4};
}
// operator overloading
friend std::vector<double> operator+(fieldname one, fieldname two) {
std::vector<double> result = data[one]; // so we get the right size
for (int i = 0; i < result.size(); ++i) {
result[i] = data[one][i] + data[two][i];
}
return result;
}
};
int main() {
Domain d;
std::vector<double> temp = Domain::fieldname::x_ + Domain::fieldname::y_;
for (auto item : temp) std::cout << item << std::endl;
return 0;
}
I think it is evident from the code what I am trying to accomplish. Could someone suggest how the operator + can be overloaded so that the enum classes can be used as a proxy for vectors which are members of a class?

Arduino C++ classes needing each other

Here an example relating to my problem:
class classA
{
private:
int Value = 100;
public:
int get_Value()
{
return Value;
}
void set_Value(int p)
{
if (p == 0) Value = B.get_Value();
else Value = 5;
}
};
classA A = classA();
class classB
{
private:
int Value = 200;
public:
int get_Value()
{
return Value;
}
void set_Value(int p)
{
if (p == 0) Value = A.get_Value();
else Value = 5;
}
};
classB B = classB();
The problem is that class A can't access class B because it's definition is below it's own. My question is how can I define it so that class A has access to class B.
I tried to something like class classB; or class classB; classB B = classB; before classA begins.
Because I'm relatively new to programming I don't know how to solve such (probably easy) problems. Hope for some help!
This is a problem with circular dependencies. Luckily this one is pretty easy to fix: Just put the declaration and definition into separate files.
ClassA.h:
// Include guards to prevent double includes
#ifndef CLASS_A_H
#define CLASS_A_H
class classA
{
private:
int Value = 100;
public:
// Here we only declare, but not define the functions
int get_Value();
void set_Value(int p);
};
#endif // CLASS_A_H
ClassB.h:
// Include guards to prevent double includes
#ifndef CLASS_B_H
#define CLASS_B_H
class classB
{
private:
int Value = 200;
public:
// Here we only declare, but not define the functions
int get_Value();
void set_Value(int p);
};
#endif // CLASS_B_H
And now we need to actually define the functions, but in different files
ClassA.cpp:
#include "A.h"
#include "B.h"
// Use extern to tell the compiler that this declaration can be
// found in any of the other files and it will not complain as
// long as it is found somewhere
extern classB B;
int classA::get_Value()
{
return Value;
}
void classA::set_Value(int p)
{
if (p == 0) Value = B.get_Value();
else Value = 5;
}
ClassB.cpp:
#include "A.h"
#include "B.h"
// Use extern to tell the compiler that this declaration can be
// found in any of the other files and it will not complain as
// long as it is found somewhere
extern classA A;
int classB::get_Value()
{
return Value;
}
void classB::set_Value(int p)
{
if (p == 0) Value = A.get_Value();
else Value = 5;
}
Then, in your main file just include the two headers and you're good to go:
#include "A.h"
#include "B.h"
classB B = classB();
classA A = classA();
By the way, when you're on Arduino you can just create new .h and .cpp files and put them next to the .ino file and it should be found. You can even put them in folders, but then the include paths must be relative to each files, for example: #include "../include/file.h"

member function as callback

I would like to pass a member function of an instantiated object to another function. Example code is below. I am open for any strategy that works, including calling functional() from another function inside memberfuncpointertestclass using something like lambda or std::bind. Please note that I did not understand most of the threads I found with google about lambda or std::bind, so please, if possible, keep it simple. Also note that my cluster does not have C++ 11 and I would like to keep functional() as simple as it is. Thank you!
int functional( int (*testmem)(int arg) )
{
int a = 4;
int b = testmem(a);
return b;
}
class memberfuncpointertestclass
{
public:
int parm;
int member( int arg )
{
return(arg + parm);
}
};
void funcpointertest()
{
memberfuncpointertestclass a;
a.parm = 3;
int (*testf)(int) = &a.member;
std::cout << functional(testf);
}
int main()
{
funcpointertest();
return 0;
}
You cannot invoke a method on an object without an instance to refer to. So, you need to pass in both the instance as well as the method you want to invoke.
Try changing functional to:
template <typename T, typename M>
int functional(T *obj, M method)
{
int a = 4;
int b = (obj->*(method))(a);
return b;
}
And your funcpointertest to:
void funcpointertest()
{
memberfuncpointertestclass a;
a.parm = 3;
std::cout << functional(&a, &memberfuncpointertestclass::member);
}
This is a job for std::function, a polymorphic function wrapper. Pass to functional(...) such a function object:
#include <functional>
typedef std::tr1::function<int(int)> CallbackFunction;
int functional(CallbackFunction testmem)
{
int a = 4;
int b = testmem(a);
return b;
}
then use std::bind to create a function object of the same type that wraps memberfuncpointertestclass::method() of instance a:
void funcpointertest()
{
memberfuncpointertestclass a;
a.parm = 3;
CallbackFunction testf = std::bind(&memberfuncpointertestclass::member, &a, std::placeholders::_1);
std::cout << functional(testf);
}
Check this item for more details.

Fibonacci Sequence error

I am coding a Fibonacci sequence in Eclipse and this is my code-
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public int increment() {
int temp = b;
b = a + b;
a = temp;
return value;
}
public int getValue() {
return b;
}
}
It is showing an error in the return value; line saying value cannot be resolved to a variable. I don't see any other errors.
Where is value defined? You return something that was not defined anywhere.
You don't have a "value" defined, this is your error. I don't remember the thing exactly, but I think you don't need a and b, I found this in my code archive, hope it helps.
public class Fibonacci
{
public static long fibo(int n)
{
if (n <= 1) return n;
else return fibo(n - 1) + fibo(n - 2);
}
public static void main() {
int count = 5; // change accordingly, bind to input etc.
int N = Integer.parseInt(count);
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fibo(i));
}
}
In case you want to stay with your own code, try returning "b" as value.
Your method is returning an int variable so you would have to define and return value as an int
I am not sure what you trying to do.
If you have "getValue" method I think "increment" method should be void.
When you want current Fibonacci value use "getValue" method.
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public void increment() {
int temp = b;
b = a + b;
a = temp;
}
public int getValue() {
return b;
}