How do I switch both parameters of the class to the object that I am creating? What is the syntax? (They must receive all the same parameters)
#include <iostream>
using namespace std;
class MyClass
{
public:
MyClass(int x,int y):value(x),value2(y)
{
//nothing
}
int value=10;
int value2;
};
int main()
{
MyClass ob1[5]; //Here! What is the correct syntax?
cout << ob1[0].value << endl;
return 0;
}
You can use
MyClass ob1[] = {{1,2},{2,3},{3,4},{4,5},{5,6}};
(if you're using C++11 or later).
However, it would be better to use a std::vector or std::array.
Try these two
MyClass ob1[5] = {{1,1},{2,2},{3,3},{4,4},{5,5}};
OR
MyClass ob1[5] = {MyClass(1,1), MyClass(2,2), MyClass(3,3), MyClass(4,4), MyClass(5,5)};
Related
I am very new to pointers, so I have no idea what is going on with them.
I am trying to get a master class pass a pointer of itself to its worker/s, and I have no idea why it doesn't work.
#include <iostream>
#include <Windows.h>
using namespace std;
class BigOne {
public:
LittleOne workers[1] = {LittleOne(this)};
int increase = 0;
};
class LittleOne {
BigOne* master;
public:
LittleOne(BigOne*);
void Increment();
};
LittleOne::LittleOne(BigOne* upOne) {
master = upOne;
}
void LittleOne::Increment() {
master->increase++;
}
BigOne Outer;
int main() {
cout << Outer.increase << endl;
Outer.worker.Increment();
cout << Outer.increase << endl;
system("PAUSE");
}
This is my problem boiled down to its core components.
The problem isn't with pointers. It's mostly here:
class BigOne {
public:
LittleOne workers[1] = {LittleOne(this)};
int increase = 0;
};
When you define workers, what is LittleOne? How is it laid out in memory? How is it initialized? The compiler can't know, it hasn't seen the class definition yet. So you must flip the definitions around:
class BigOne;
class LittleOne {
BigOne* master;
public:
LittleOne(BigOne*);
void Increment();
};
class BigOne {
public:
LittleOne workers[1] = {LittleOne(this)};
int increase = 0;
};
The forward declaration allows us to define members that accept and return pointers. So the class LittleOne can have its definition written before BigOne. And now BigOne can define members of type LittleOne by value.
The issue is with forward declaration.
You can refer the following link for more details and explanation.
What are forward declarations in C++?
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;
};
The code should explain my difficulty. Though the code itself is quite meaningless, I'm planning to add containers in MyClass, and use algorithms with member functions.
#include <cstdlib>
#include <algorithm>
#include <functional>
using namespace std;
class MyClass
{
public:
MyClass() { a = 0; }
~MyClass() {}
private:
int a;
bool tiny_test (int);
int Func();
};
bool MyClass::tiny_test (int b)
{
return a == b;
}
int MyClass::Func()
{
// does not compile
(mem_fun(&MyClass::tiny_test))(this);
// commented below is another attempt, also no success
//mem_fun1_t<bool, MyClass, int> tmp_functor = mem_fun(&MyClass::tiny_test);
//tmp_functor(this);
return 0;
}
int main(int argc, char** argv)
{
return 0;
}
Thanks a lot! Btw, I'm not using a static member function, simply because I believe it must work for non-static member functions.
P.S. Eric, Jarod42, thanks for prompt replies!
bool MyClass::tiny_test (int b)
{ // ^^^^^ You missed this argument
return a == b;
}
Try this:
// Supply one more argument. E.g., 3
(mem_fun(&MyClass::tiny_test))(this, 3);
How do you use a pointer and call the class methods it points to?
For example:
Image *img[26];
Image IM = outputImage();
img[0] = &IM;
I want to call img[0], or IM's methods. I tried something like this but I received errors.
img[0].getPixel(0,1);
The error is "expression must have a class type"
Since you are using a pointer array, you must dereference it as a pointer.
img[0]->getPixel(0, 1);
And this:
Image IM = outputImage();
should be:
Image &IM = outputImage();
Assuming that outputImage() returns a reference.
you can use following two methods:
1) use -> operator to the member function.
#include<iostream>
using namespace std;
class myclass
{
public:
void printHello()
{
cout<<"hello from class"<<endl;
}
};
int main()
{
myclass *s[10];
myclass inst;
s[0]=&inst;
s[0]->printHello();
return 0;
}
2) use . after de-referencing the pointer.
#include<iostream>
using namespace std;
class myclass
{
public:
void printHello()
{
cout<<"hello from class"<<endl;
}
};
int main()
{
myclass *s[10];
myclass inst;
s[0]=&inst;
(*s[0]).printHello();
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.