I'm trying to create an array of objects within another object and decide the magnitude of the array.
Why I get an error when I try to assign "obj2T" to "obj2"?
Pastebin code link: https://pastebin.com/kujujP5N
What is the correct syntax for creating an array of objects within another object and decide the magnitude of the array?
#include <iostream>
using namespace std;
class classe2
{
public:
classe2();
protected:
private:
};
class classe1
{
public:
classe1(int value);
void setClasse()
{
classe2 obj2T[grandezza];
obj2=obj2T;
}
protected:
private:
const int grandezza;
classe2 obj2[];
};
int main()
{
cout << "Hello World!" << endl;
return 0;
}
Error:
C:\cppProjects\project\main.cpp||In member function 'void classe1::setClasse()'
C:\cppProjects\project\main.cpp|22|error: incompatible types in assignment of 'classe2 [((classe1*)this)->classe1::grandezza]' to 'classe2 [0]'
The correct syntax is
#include <vector>
...
class classe1
{
public:
classe1(int value) :
obj2 (value)
{
}
private:
std::vector<classe2> obj2;
};
Related
why gcc 9.4 not check parameters when bind a class member funtion to a std::function viriable, but check when bind a global function? here is example code, CreateRpcFun has a parameter, but Test member function print doesn't have any other parameters except this, bind print to CreateRpcFun works well, but global funtion print2 cannot, can anybody explain why?
#include <functional>
#include <iostream>
#include <string>
using namespace std;
using CreateRpcFun = std::function<void(const string &)>;
class Test {
public:
Test() : str_("nihao!") {}
// bind print to CreateRpcFun passed compile
void print() { cout << str_ << endl; }
private:
string str_;
};
class Holder {
public:
CreateRpcFun CreateRpc;
};
class Other {
public:
Other(Holder h, string str) : h_(h), str_(str) {}
void run() { h_.CreateRpc("world!"); }
private:
Holder h_;
string str_;
};
void print1(const string &str) { cout << str << endl; }
void print2() { cout << "magic" << endl; }
int main() {
Test t;
Holder h;
h.CreateRpc = std::bind(&Test::print, &t);
Other o(h, "hhhh");
o.run();
h.CreateRpc = &print1;
h.CreateRpc("test");
// h.CreateRpc = &print2; // compile error
// h.CreateRpc("test");
}
In following code, i get an error on line 33. Why? What is the correct syntax?
Surely I made some stupid mistake ... unfortunately I'm trying to better understand the vectors.
#include <iostream>
#include <vector>
class firstClass
{
public:
firstClass(int x, int y):sum(x+y)
{
}
void getSum()
{
std::cout << sum << std::endl;
}
private:
int sum;
};
class secondClass
{
public:
secondClass(int dim)
{
obj = new std::vector<firstClass>(dim,firstClass{3,5});
}
private:
std::vector<firstClass>*obj;
};
int main()
{
secondClass*obj2;
obj2 = new secondClass(4);
obj2->(*obj)[0].getSum(); //HERE!
return 0;
}
Error:
error: expected unqualified-id before '(' token
error: 'obj' was not declared in this scope
The correct syntax for accessing the data member should be:
(*(obj2->obj))[0].getSum();
Note that secondClass::obj is private data member, so you can't access it in main().
For code sample you showed, you don't need to use raw pointer and new at all.
I have a simple class which I cannot instantiate and I don't know why...
Please help me !
-------Test.cpp-------
#include<iostream>
using namespace std;
#include "meteo.h"
int main()
{
Meteo meteo;
}
-------meteo.h---------
#ifndef METEO_H
#define METEO_H
class Meteo
{
public:
Meteo();
int Get(int i);
private:
char *list[];
};
#endif
-------meteo.cpp--------
#include "meteo.h"
Meteo::Meteo()
{
list[]("Sec","Venteux","Humide");
}
int Meteo::Get(int i)
{
return list[i];
}
I get the error: "undefined reference to `Meteo::Meteo()'"
It seems that the problem is that the compiler issued an error when was compiling the constructor
Meteo::Meteo()
{
list[]("Sec","Venteux","Humide");
}
and did not generate the object module.
This record
list[]("Sec","Venteux","Humide");
is invalid.
Try to change the class definition like
class Meteo
{
public:
Meteo();
int Get(int i);
private:
const char *list[3];
};
and define the constructor like
Meteo::Meteo() : list { "Sec","Venteux","Humide" }
{
}
The other reason might be that you did not include object module meteo in the project.
Take into account that this member function
int Meteo::Get(int i)
{
return list[i];
}
is also wrong. The type of elements of the array is const char * not int.
I have made a map of functions. all these functions are void and receive single string parameter.
code:
void f1(string params){...}
void f2(string params){...}
void f3(string params){...}
map<string , void*> funcMap;
funcMap["f1"] =(void*)&f1;
funcMap["f2"] =(void*)&f2;
funcMap["f3"] =(void*)&f3;
how do i call a function?
I tried the next code, but id doesn't work:
void (*func)(string) = &funcMap[commandType];
func(commandParam);
I get this error message:
Server.cpp:160:46: error: cannot convert ‘void**’ to ‘void (*)(std::string) {aka void (*)(std::basic_string<char>)}’ in initialization
using pfunc = void (*)(string);
map<string, pfunc> funcMap;
funcMap["f1"] = f1; //and so forth
And then call:
pfunc f = funcMap[commandType];
(*f)(commandParam);
In general, why throw away type safety? If it's a map of function pointers, declare it to be one.
Why not just have those as separate classes.
Then have the methods as virtual.
You can then have a map between the string and the base class.
i.e.
class Someoperation
{
virtual void Doit() = 0;
};
map<string, Someopertion> ops;
Then
class MyOp : public Someoperation
{
void Doit() { /* Some code here */}
};
Just add objects
ops["Hello"] = MyOp();
then call it
ops["Hello"].Doit();
&funcMap[commandType]
Just drop the &. Your compile error was useful here. It had a void** on the right which is because you took the address of a function pointer. You don't want two levels of indirection there.
Try C++ style. It has overhead for allocation and inheritance, but it's more flexible and extensible if you'll need some more functionality in the future.
#include <iostream>
#include <string>
#include <unordered_map>
#include <memory>
using namespace std;
class Someoperation {
public:
virtual void Doit() = 0;
};
class MyOp1 : public Someoperation {
public:
void Doit() final { cout << "MyOp1" << endl; }
};
class MyOp2 : public Someoperation {
public:
void Doit() final { cout << "MyOp2" << endl; }
};
int main() {
unordered_map<string, unique_ptr<Someoperation> > ops;
ops["1"] = unique_ptr<Someoperation>(new MyOp1);
ops["2"] = unique_ptr<Someoperation>(new MyOp2);
ops["1"]->Doit(); // Out: MyOp1
ops["2"]->Doit(); // Out: MyOp2
return 0;
}
#include <iostream>
using namespace std;
class B
{
public:
int getMsg(int i)
{
return i + 1;
}
};
class A
{
B b;
public:
void run()
{
taunt(b.getMsg);
}
void taunt(int (*msg)(int))
{
cout << (*msg)(1) << endl;
}
};
int main()
{
A a;
a.run();
}
The above code has a class B inside a class A, and class A has a method taunt that takes a function as an argument. class B's getMsg is passed into taunt...The above code generated the following error message: "error: no matching function for call to 'A::taunt()'"
What's causing the error message in the above code? Am I missing something?
Update:
#include <iostream>
using namespace std;
class B
{
public:
int getMsg(int i)
{
return i + 1;
}
};
class A
{
B b;
public:
void run()
{
taunt(b.getMsg);
}
void taunt(int (B::*msg)(int))
{
cout << (*msg)(1) << endl;
}
};
int main()
{
A a;
a.run();
}
t.cpp: In member function 'void A::run()':
Line 19: error: no matching function for call to 'A::taunt()'
compilation terminated due to -Wfatal-errors.
I'm still getting the same error after changing (*msg)(int) to (B::*msg)(int)
b.getMsg is not the correct way to form a pointer to member, you need &B::getMsg.
(*msg)(1) is not the correct way to call a function through a pointer to member you need to specify an object to call the function on, e.g. (using a temporary) (B().*msg)(1).
The right way to do such things in OOP is to use interfaces so all you need to do is to define an interface and implement it in B class after that pass the pointer of instance which implements this interface to your method in class A.
class IB{
public:
virtual void doSomething()=0;
};
class B: public IB{
public:
virtual void doSomething(){...}
};
class A{
public:
void doSomethingWithB(IB* b){b->doSomething();}
};
This works in VS 2010. The output is the same on all lines:
#include <iostream>
#include <memory>
#include <functional>
using namespace std;
using namespace std::placeholders;
class A
{
public:
int foo(int a, float b)
{
return int(a*b);
}
};
int main(int argc, char* argv[])
{
A temp;
int x = 5;
float y = 3.5;
auto a = std::mem_fn(&A::foo);
cout << a(&temp, x, y) << endl;
auto b = std::bind(a, &temp, x, y);
cout << b() << endl;
auto c = std::bind(std::mem_fn(&A::foo), &temp, _1, y);
cout << c(5) << endl;
}
Basically, you use std::mem_fn to get your callable object for the member function, and then std::bind if you want to bind additional parameters, including the object pointer itself. I'm pretty sure there's a way to use std::ref to encapsulate a reference to the object too if you'd prefer that. I also included the _1 forwarding marker just for another way to specify some parameters in the bind, but not others. You could even specify everything BUT the class instance if you wanted the same parameters to everything but have it work on different objects. Up to you.
If you'd rather use boost::bind it recognizes member functions and you can just put it all on one line a bit to be a bit shorter: auto e = boost::bind(&A::foo, &temp, x, y) but obviously it's not much more to use completely std C++11 calls either.