Imagine I have a class and it has a private value for example this value name is a, then I set it's value to 10.
How I can access to this variable with its value (10) in another class?
(I do not want to use friend function and friend class)
a.h
#include <iostream>
using namespace std;
static int s=0;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
class a
{
private:
public:
void sets(int );
};
a.cpp
#include "a.h"
void a::sets(int y){
cin >> y;
s=y;
}
main.cpp
#include"a.h"
int main()
{
int i=0;
int q;
a a1;
a1.sets(q);
cout << s+1 << endl;
for (i=1; i<5; i++){
if (s == i) cout << "ok";
}
}
If you do not want to use friendship, add a public interface to this variable (setter and/or getter class members).
Either make the variable public or add a function to get the value that returns it, like int getA() const { return a; } .
Use a private member s in your class a instead of a global variable, and access it via public Getter function GetS
Example:
#include <iostream>
using namespace std;
class a
{
private:
int s;
public:
void SetS() { cin >> s; }
int GetS() const { return s; }
};
int main()
{
a a1;
a1.SetS();
int s1=a1.GetS();
cout << s1+1 << endl;
for (int i=1; i<5; i++){
if (s1 == i) cout << "ok";
}
}
Related
I create a class, and in the class I declare a friend function so that I can later change a private value with an if..else statement, though I can't even change it without the if..else.
#include <iostream>
using namespace std;
class A {
private:
float money;
friend void _setMoney(A a, float i);
public:
void setMoney(float i) {
money = i;
};
float getMoney() {
return money;
};
A(float i) {
i = money;
};
};
void _setMoney(A a, float i) {
a.setMoney(i);
};
int main(){
A a(0);
cout << a.getMoney() << endl;
a.setMoney(10);
cout << a.getMoney() << endl;
_setMoney(a, 20);
cout << a.getMoney() << endl;
}
After executing this in VS Code, I get 0, 10, 10 instead of 0, 10, 20.
The problem is not with _setMoney() being a friend or not. If that were the issue, your code would not even compile.
The real issue is that you are passing the a object in main() by value to _setmoney(), so you are passing in a copy of the object, and are then modifying the copy rather than the original object.
Simply pass the object by reference instead:
void _setMoney(A& a, float i) {
a.setMoney(i);
};
That being said, A::setMoney() is public, so _setMoney() does not need to be a friend of A in order to call it. Only if _setMoney() wanted to access A::money directly, eg:
void _setMoney(A& a, float i) {
a.setMoney(i); // <-- friend not required for this
a.money = i; // <-- friend required for this
};
#include <iostream>
using namespace std;
class A {
private:
float money;
//////////////////////////////////////////////////////////
friend void _setMoney(A& a, float i);
//////////////////////////////////////////////////////////
public:
void setMoney(float i) {
//////////////////////////////////////////////////////////
money = i;
//////////////////////////////////////////////////////////
}
float getMoney() {
return money;
}
A(float i) {
money = i;
}
};
//////////////////////////////////////////////////////////
void _setMoney(A& a, float i) {
a.money = i; // friend privilege
}
//////////////////////////////////////////////////////////
int main(){
A a(0);
cout << a.getMoney() << endl;
a.setMoney(10);
cout << a.getMoney() << endl;
_setMoney(a, 20);
cout << a.getMoney() << endl;
return 0;
}
class A
{
int id;
public:
A (int i) { id = i; }
void show() { cout << id << endl; }
};
int main()
{
A a[2];
a[0].show();
a[1].show();
return 0;
}
I get an error since there is no default constructor.However thats not my question.Is there a way that ı can send parameters when defining
A a[2];
A good practice is to declare your constructor explicit (unless it defines a conversion), especially if you have only one parameter. Than, you can create new objects and add them to your array, like this :
#include <iostream>
#include <string>
class A {
int id;
public:
explicit A (int i) { id = i; }
void show() { std::cout << id << std::endl; }
};
int main() {
A first(3);
A second(4);
A a[2] = {first, second};
a[0].show();
a[1].show();
return 0;
}
However, a better way is to use vectors (say in a week you want 4 objects in your array, or n object according to an input). You can do it like this:
#include <iostream>
#include <string>
#include <vector>
class A {
int id;
public:
explicit A (int i) { id = i; }
void show() { std::cout << id << std::endl; }
};
int main() {
std::vector<A> a;
int n = 0;
std::cin >> n;
for (int i = 0; i < n; i++) {
A temp(i); // or any other number you want your objects to initiate them.
a.push_back(temp);
a[i].show();
}
return 0;
}
What I want to do (c++ problem):
Enter main. Call Class A (and pass a value). Inside class A, I call Class B (and pass a value). Do some stuff in class B. Return value back to Class A. Do some more stuff in A. Return back to main function.
I get the error that obj3 is an unknown override specifier. I tried to create a simple program to showcase my problem;
#include <math.h>
#include <string>
#include <stdio.h>
#include <iomanip>
#include <iostream>
using namespace std;
class A
{
B obj3;
public:
int add3(int num)
{
int x = num + 1;
int y = obj3.add2(x);
return y;
}
};
class B
{
public:
int add2(int num2)
{
int y = num2 + 2;
return y;
}
};
int main()
{
int g;
A obj1;
cout << "enter a number: " << endl;
cin >> g;
int r = obj1.add3(g);
cout << r;
system("pause");
return 0;
}
I am trying to access the elements of a virtual function which is declared in Class 1 and then defined in Class 2. I understand that the std :: out_of_range error is a memory access problem, but I don't understand the problem in the code main () to access the values.
When calling the function ** m-> function (t, j) ** I cannot access the elements of * parmem *, but if I directly call the output of the function it works: ** parmem.at (1). gamma **. Here is the code:
Class 1:
#include <armadillo>
#include <iostream>
using namespace std;
using namespace arma;
class Class1
{
public:
mat Y;
struct Par
{
mat gamma;
} par;
std::vector<Par> parmem ;
virtual double function( const int t, const int j ) = 0;
};
Class 2:
class Class2 : public Class1
{
public:
virtual double function( const int t, const int j );
};
double Class2::function( const int t, const int j )
{
cout << parmem.at(t).gamma << endl;
return j+t;
}
main()
int main()
{
mat Y=randu<mat>(3,3);
int t=1;
int j=1;
Class2 *m = new Class2;
std::vector<Class1::Par> parmem {
{Y},
{2*Y}
};
cout << parmem.at(1).gamma << endl; //funciona
cout << m->function(t,j) << endl; //no funciona
return 0;
}
Thanks for the info.
In the following lines, you create independent objects:
Class2 *m = new Class2;
std::vector<Class1::Par> parmem {
{Y},
{2*Y}
};
The std::vector<Class1::Par> parmem {{Y},{2*Y}}; is not part of the instance of the object m is pointing at.
It should work if you assign parmem to the object m points on by adding m->parmem = paramen; to the code.
int main()
{
mat Y=randu<mat>(3,3);
int t=1;
int j=1;
Class2 *m = new Class2;
std::vector<Class1::Par> parmem {
{Y},
{2*Y}
};
m->parmem = paramen;
cout << parmem.at(1).gamma << endl; //funciona
cout << m->function(t,j) << endl; //no funciona
return 0;
}
I have one application in which following task are to be done
1.) UI application will send command code (integer value).
2.) DLL interface(in c++) will get that integer value and execute corresponding command function.
commands name and command code are maintained as
#define PING 50
there will be 500 commands and applying SWITCH CASE will not sound good. so i decided to implement function pointer in my code as below
#include "stdafx.h"
#include<iostream>
#define PING 20
using namespace std;
//extern const int PING = 10;
void ping()
{
cout<<"ping command executed";
}
void get_status(void)
{
cout<<"Get_status called"<<endl;
}
class ToDoCommands
{
public:
void getCommand( void (*CommandToCall)() );
};
void ToDoCommands::getCommand( void (*CommandToCall)())
{
void (*CommandToCall1)();
CommandToCall1 = CommandToCall;
CommandToCall1();
}
int main()
{
int code;
ToDoCommands obj;
cout<<"enter command code";
cin>>code; // if UI send 50 then Ping function get executed as #define PING 50
obj.getCommand(ping); // here m passing ping manually..
//obj.getCommand(get_status);
return 0;
}
how can i pass command name corresponding to command code in
obj.getCommand(ping);
You are almost there: make a std::map of std::string to function pointer, initialize it with data pairing a string name to a corresponding function pointer, and then use that map at runtime to pick the correct pointer based on the string parameter passed in.
#include <iostream>
#include <string>
#include <map>
using namespace std;
void ping() {
cout << "ping" << endl;
}
void test() {
cout << "test" << endl;
}
int main() {
map<string,void(*)()> m;
m["ping"] = ping;
m["test"] = test;
// I am using hard-coded constants below.
// In your case, strings will come from command line args
m["test"]();
m["ping"]();
return 0;
}
Link to a demo with std::map.
Here is how you can do it without a map (it will be slower because of the linear search, but you can fix it by ordering names alphabetically and using binary search).
#include <iostream>
#include <cstring>
using namespace std;
void ping() {
cout << "ping" << endl;
}
void test() {
cout << "test" << endl;
}
typedef void (*fptr_t)();
int main() {
const fptr_t fptrs[] = {test, ping};
const char *names[] = {"test", "ping"};
const char *fname = "test";
for (int i = 0 ; i != 2 ; i++) {
if (!strcmp(fname, names[i])) {
fptrs[i]();
break;
}
}
return 0;
}
Link to a demo with arrays.
Declare an array of function pointers. Where you treat the index as your "code". For example:
void foo(){
printf("foo\n");
}
void bar(){
printf("bar\n");
}
int main(void)
{
void (*code_to_function[100])();
int code;
code_to_function[0] = foo;
code_to_function[1] = bar;
printf("Enter code: ");
scanf("%d", &code);
code_to_function[code]();
return 0;
}
Please note that for this rudimentary example, inputting integer code other than 0 and 1 will result in a segfault.
I should say #dasblinkenlight is right but if you don't want to use std::map you should implement a map yourself. This can be buggy and not a optimized way, but if you don't want to use STL, it seems you should implement it yourself.
You can use 2 arrays with corresponding indices. One of them is a char * array and another one is function pointers. They are better to be encapsulated in a class named something like MyMap.
class MyMap {
public:
...
inline void add(char *name, (void (*ptr)(void)) ) {
names_[currIndex_] = name; // Or stcpy
ptrs_[currIndex_] = ptr;
currIndex_++;
}
inline (void(*)(void)) get(char *name) {
int foundIndex = -1;
for (int i = 0; i < currIndex_; i++) {
// Find matching index
}
if (foundIndex_ >= 0) {
return ptrs_[foundIndex_];
}
return NULL;
}
private:
int currIndex_;
char *names_[10];
(void (*ptrs_[10])(void));
};