object as key to map becomes const in cpp - c++

can someone please explain why the following code compilation fails with message "passing ‘const apple’ as ‘this’ argument of ‘int apple::foo()’ discards qualifiers", and how to resolve it.
#include <cstdlib>
#include <iostream>
#include <string>
#include <map>
using namespace std;
/*
*
*/
class apple{
private:
int a,b,c,d;
public:
int foo(){
return a+b+c+d;
}
};
class ball{
private:
map<apple,string> mp;
public:
void foo2(){
for(map<apple,string>::iterator it = mp.begin();it!=mp.end();++it){
cout<<it->first.foo()<<endl;
}
}
}
int main(int argc, char** argv) {
return 0;
}

Works for me: (added const at the end of foo() and ; on end of ball class). Class apple is a Key in std::map which is declared as const: typedef pair value_type; so accessing key should be also declared as const.
#include <map>
#include <iostream>
using namespace std;
class apple{
private:
int a,b,c,d;
public:
int foo() const {
return a+b+c+d;
}
};
class ball{
private:
map<apple,string> mp;
public:
void foo2(){
for(map<apple,string>::iterator it = mp.begin();it!=mp.end();++it){
cout<<it->first.foo()<<endl;
}
}
};
int main(int argc, char** argv) {
return 0;
}

Related

How can I write a function that returns to array inside the header?

I am trying to create a function that returns in main.cpp in the header and .cpp file and run it in the main function.
This process I do works on main.
#include <iostream>
#include <sstream>
#include "Cards.h"
using namespace std;
//this function returns array
int *function1(){
int a=12;
int b=13;
int c=14;
static int list[3]={a,b,c};
return list;
}
int main(int argc, const char * argv[]) {
int *list;
list=function1();
cout<<list[1]<<endl;
return 0;
}
However, I cannot do these in a header and a separate cpp file.
I have a Cards header
#ifndef Cards_H
#define Cards_H
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
class Cards{
public:
char suit; //A,H,D,C,S. A is empty card
int number; //00-13
int visibilty;//0 - 1. O invisible 1 is visible
int * function2();
};
#endif
This is the class cpp file
#include "Cards.h"
using namespace std;
//function
int Cards:: function2(){
int a=12;
int b=13;
int c=14;
int list[3]={a,b,c};
return list; // error code Cannot initialize return object of type 'int Cards::*' with an lvalue of type 'int [3]'
}
How do I fix this problem and run it in main?
As pointed out in the comments, there is already a SO thread
Return array in a function
which handles your issue.
If your really want to use C arrays then your program shall look like:
Cards_CStyle.h:
#ifndef Cards_CStyle_H
#define Cards_CStyle_H
using namespace std;
class Cards {
public:
int* function2(int arr[]);
};
#endif
Cards_CStyle.cpp:
#include "Cards_CStyle.h"
using namespace std;
//function
int* Cards::function2(int arr[]){
int a=12, b=13, c=14;
arr[0] = a;
arr[1] = b;
arr[2] = c;
return arr;
}
main_CStyle.cpp:
#include <iostream>
#include "Cards_CStyle.h"
using namespace std;
int main(int argc, const char * argv[]) {
int arr[3]; // Take care that all your functions use size <= 3
Cards cards;
int* list=cards.function2(arr);
cout<<list[1]<<endl;
return 0;
}
As recommended in the comments, you should use the containers of the STL, e.g. array for fixed length or vector for variable length. Assuming that fixed length of 3 will be fine for you, then your code would be looking like this:
Cards_STLStyle.h:
#ifndef Cards_STLStyle_H
#define Cards_STLStyle_H
#include<array>
using namespace std;
typedef array<int, 3> my_array;
class Cards {
public:
my_array function2();
};
#endif
Cards_STLStyle.cpp:
#include "Cards_STLStyle.h"
using namespace std;
//function
my_array Cards::function2(){
int a=12, b=13, c=14;
return my_array { a,b,c};
}
main_STLStyle.cpp:
#include <iostream>
#include <array>
#include "Cards_STLStyle.h"
using namespace std;
int main(int argc, const char * argv[]) {
Cards cards;
my_array list=cards.function2();
cout<<list[1]<<endl;
return 0;
}
Please find more information here:
array

how transfer function from template class

#include <iostream>
#include <windows.h>
#include <string.h>
#include <functional>
#include <stdint.h>
#include <stdio.h>
using namespace std;
template <typename T>
class someclass {
public:
T value;
int sum(int vl1, int vl2) { return vl1 + vl2; };
};
template <typename T>
class someclass2 {
public:
T value;
void print(const std::function<int(int, int)>& func) {
cout << func(3, 4) << '\n';
};
};
int main(int argc, const char **argv)
{
someclass<int> obj1;
someclass2<int> obj2;
obj2.print(obj1.sum);
}
Compiler show error on last line : error C3867: 'someclass::sum': non-standard syntax; use '&' to create a pointer to member
Note that
int sum(int vl1, int vl2) { return vl1 + vl2; };
doesn't use its owner class' member in any way, it safely can be declared static, in that case this code would work.
The problem with this code is that a member function got a different type from standalone function. It's a member of class someclass, so its type is int (someclass::*)(int, int) and to call it you need an instance of that class.
The literal solution in general case is to hide pass of this inside the functor created by lambda expression:
obj2.print( [&](int a, int b)-> int { return obj1.sum(a,b); } );
You can use std::bind to do that
int main(int argc, const char **argv)
{
someclass<int> obj1;
someclass2<int> obj2;
using namespace std::placeholders;
obj2.print(std::bind(&someclass<int>::sum, &obj1, _1, _2));
}

std::stol corrupts stack on failure

class.h
// class.h
#pragma once
#include <string>
#include <iostream>
class TV {
public:
TV() {}
TV(std::string, std::string, std::string, std::string, std::string);
private:
int member;
};
main.cpp:
//main.cpp
#include "class.h"
TV::TV(std::string a, std::string b, std::string c, std::string d, std::string e) {
try {
member = std::stol(a);
if (member <= 0)
throw;
}
catch (...) {
std::cout << "Invalid argument" << std::endl;
}
}
int main(int argc, char *argv[]) {
new TV("TEST","NAME","0.1","0.1","0.1");
};
So it turns out that if I provided std::stol with an invalid_argument, then in gdb all other arguments passed to the function would appear corrupted.
Can anyone explain why this happens?

How do I call a class by passing it's object and member function to another function in c++?

How do I execute a member's function by passing the object and the member's function to another function in c++. I do understand the answer to my question is out there; however, I do not know what this is called. So far I created 2 files, exeFunc.h and exeFunc.cpp. Their code consist of:
exeFunc.h
/*
File: exeFunc.h
Header file for exeFunc Library.
*/
#ifndef EXEFUNC_H
#define EXEFUNC_H
#include "mbed.h"
#include "msExtensions.h"
#include "cfExtensions.h"
#include <map>
class exeFunc
{
public:
exeFunc(msExtensions &msExt, cfExtensions &cfExt);
private:
void _splitFuncFromCmd();
void _attachCallback();
msExtensions &_msExt;
cfExtensions &_cfExt;
//FunctionPointer _p;
};
#endif
exeFunc.cpp
/*
File: exeFunc.cpp
Execute functions in other Sensor libraries/classes
Constructor
*/
#include "mbed.h"
#include "ConfigFile.h"
#include "msExtensions.h"
#include "cfExtensions.h"
#include "exeFunc.h"
#include <map>
#include <string>
using namespace std;
exeFunc::exeFunc(msExtensions &msExt, cfExtensions &cfExt) : _msExt(msExt), _cfExt(cfExt)
{
//_cfExt.checkConfigForFirstStart();
//_p.attach(&_cfExt, &cfExtensions::checkConfigForFirstStart);
//_p.call();
}
void exeFunc::_splitFuncFromCmd()
{
}
void exeFunc::_attachCallback()
{
}
I wrote a completed example, may helps
class MyClass
{
public:
MyClass(int b)
:_b(b)
{
}
int Foo(int a)
{
return a * _b;
}
int _b;
};
typedef int (MyClass::*MFP)(int);
int get_result(MyClass* obj, MFP mfp)
{
int r = (obj->*mfp)(5); // 30
return r;
}
int _tmain(int argc, _TCHAR* argv[])
{
MFP mfp = &MyClass::Foo;
MyClass m(6);
get_result(&m, mfp);
return 0;
}
You call it by another function.if you have an independent function.
To be honesty your question is not completely clear.However :
int F(int,int,int);
int g();
//main scope
F(g(),a,b)

Passing string as reference to function pointer c++

Below is my code
#include "stdafx.h"
#include <string.h>
#include <iostream.h>
using namespace std;
class ToDoCommands
{
public:
void getCommand(string);
};
void ToDoCommands::getCommand(string command)
{
cout<<command; //here i get ping
void (*CommandToCall)(void);
CommandToCall = command; // error here i want something like
// CommandToCall = ping
CommandToCall();
}
void ping(void)
{
cout<<"ping command executed";
}
int main()
{
ToDoCommands obj;
obj.getCommand("ping");
}
The function pointer should refer to function ping dynamically. A string same as function name is passed to getCommand function in main.
C++ just doesn't work that way. If you really need something like that, you'll have to make a table of functions that are indexed by name:
#include <assert.h>
#include <iostream>
#include <map>
#include <string>
using std::cout;
using std::string;
using std::map;
void ping(void)
{
cout << "ping command executed\n";
}
class ToDoCommands
{
public:
typedef void (*FunctionPtr)();
typedef string Name;
void registerFunction(Name name,FunctionPtr);
void callFunction(Name);
private:
map<Name,FunctionPtr> func_map;
};
void ToDoCommands::registerFunction(Name name,FunctionPtr func_ptr)
{
func_map[name] = func_ptr;
}
void ToDoCommands::callFunction(Name name)
{
assert(func_map.find(name)!=func_map.end());
func_map[name]();
}
int main(int argc,char **argv)
{
ToDoCommands to_do_commands;
to_do_commands.registerFunction("ping",ping);
to_do_commands.callFunction("ping");
return 0;
}
void ping(void)
{
// LL DD…DD XX
cout<<"ping command executed"<<endl;
}
class ToDoCommands
{
public:
void getCommand( void (*CommandToCall)(void)); //getCommand(ping)
};
void ToDoCommands::getCommand( void (*CommandToCall)(void) )
{
void (*CommandToCall1)(void);
CommandToCall1 = CommandToCall;
CommandToCall1();
}
int main()
{
ToDoCommands obj;
obj.getCommand( ping );
return 0;
}
i tried this and its working :)