so curiosity got me looking for an alternative method of returning specific data or part of a structure. I currently have a structure and class similar, if not exact to this:
struck Pos {
Int x_{0},
y_{0},
z_{0};
};
class Object {
private:
Pos xyz_{ 0, 0, 0 };
public:
const Pos getPos() { return xyz_; }
};
Now this is without constructors and stuff. Anyway the I'm trying/wanting to return the x_ of xyz_ now I could just do:
const int getPosX() { return xyz_.x_; }
but that seems impractical as I'd have to do that 3 times as well as modify my main code to compensate for the changes. So wondered if there's an easier or better method for doing something like:
Object ob; // Empty I know but you get the idea?
int xValue = ob.getPos.x_;
Any help is deeply appreciated.
ob.getPos().x_;
Worked, simply overlooked the ().
Related
This is in relation to an earlier question I had. I haven't managed to solve the problem there but for now I'm just trying to get better acquainted with the code to figure out how to deal with that problem.
Towards that goal, I've got around to trying out the suggestions given in that question and I'm a little stumped as to why the following isn't working.
in the header I have
class A {
public:
typedef std::multimap<int, double> intdoublemap_t;
const intdoublemap_t& getMap() const;
void setkey(int k);
void setvalue(double v);
void insertIntoMap();
intdoublemap_t mMapA;
private:
int key;
double value;
};
class B {
public:
typedef std::multimap<int, double> intdoublemap_t;
void mapValues(const A& a);
private:
intdoublemap_t mMapB;
};
in the implementation I have
const A::intdoublemap_t& A::getMap() const { return mMapA; }
void A::setkey(int k) { key = k; }
void A::setvalue(double v) { value = v; }
void A::insertIntoMap(){mMapA.insert(std::make_pair(key, value));}
void B::mapValues(const A & a){ const A::intdoublemap_t& mref = a.getMap();
mMapB = mref; }
and in main()
A a;
a.setkey(10);
a.setvalue(1232.2);
a.insertIntoMap();
B b;
b.mapValues(a);
The code compiles fine and everything to do with a works as expected but the map is not passing to b at all. It stays empty
Can anyone tell me why?
edit: I took another look at this and saw how to do it. I knew it was something stupidly basic. I just had to set mref in the function to a map in B and then could call a function to work on that map within B.
As #FrancoisAndrieux notes, your getMap() only sets a reference local to the function - not the class' intdoublemap_t mref. If you want the latter to be a reference to a map elsewhere, you have three options:
Make it intdoublemap_t& mref, initialize it on construction of the B instance.
Make it std::reference_wrapper<intdoublemap_t> mref, set it whenever you want (e.g. in mapValues().
Make it intdoublemap_t* (or std::shared_ptr<intdoublemap_t> in both A and B), set it whenever you like.
Note: As #FrancoisAndrieux says in a comment, with the second and third option (and without std::shared_ptr) you will have to be careful not to allow the reference to be used after the original object's lifetime has expired.
Having said all the above - I must also say that your design seems rather off to me. You should really not be doing any of these things and I'm 99% sure you're approaching your task the wrong way.
This is certainly related to a bunch of other questions which have been answered, but I have been unable to derive the answer for my specific case from them, largely because I'm not actually a programmer; I'm just an engineer who happens to have to write some code.
Here's the situation:
I have a bunch of variables I'd like to collect together, probably into a structure.
All but two I would like to initialize to zero; two specific variables (which don't happen to be the first two) need to be initialized to one.
The actual names are unique and meaningful enough that using a vector wouldn't be appropriate, plus there are some doubles in there too. I'm keeping my example below simple for clarity.
Because of the project I'm working on, I'm stuck with C++98, so even if C++11 has more elegant solutions, they won't work for me.
I am thinking something along these lines for the structure itself:
struct allFlags
{
int flagAA;
int flagAB;
int flagAC;
int flagAD;
int flagAE;
// ...
// there's about 100 variables total
// ...
int flagZZ;
};
I want to have all the flags initialized to 0 except for flagAD and flagAE, which should be 1.
So first of all, I am not sure if I should use typedef struct allFlags or struct allFlags. Next, I am not sure if I should be creating a constructor (which I think only would apply in the case of no typedef?) or making the defaults happens when I instantiate the structure. I have seen things like this (which would be put inside the struct definition):
allFlags() : flagAD(1), flagAE(1) { /*not sure of I'd need anything here*/ }
but I wouldn't want to have to list out all other ~98 variables by name individually in the constructor body to set them to zero. I have also seen things using memset which could potentially help, but I'm not sure the best way to do it.
And finally one additional related question is how to actually declare an instance of my structure (which results in the initial values I want). It looks like sometimes a struct is instantiated with the new keyword and sometimes is it treated more like a base data type, i.e. I have seen both of these in searching:
allFlags flagset1;
flagset2 = new allFlags;
I have also seen syntax which would be like this rather than using a constructor at all:
allFlags flagset3 = {}; // to zero all fields first
flagset3.flagAD = 1;
flagset3.flagAE = 1;
but I'd rather keep the instantiation as clean and simple as possible.
Please forgive the question. I have tried to do my homework before asking, but my C++ knowledge is mediocre at best and so some of the seemingly relevant answers I've found I either didn't fully understand or just raised more questions.
If you feel comfortable with using templates, you can use a class template to automate clean initialization of all member variables of allFlags.
// class template to help initialize members cleanly.
template <typename T>
struct flag
{
// Constructors
flag() : val(0) {}
flag(T const& v) : val(v) {}
// Automatic cast operators to T
operator T& () { return val; }
operator T const& () const { return val; }
// Comparison operators
bool operator==(flag const& rhs) const { return val == rhs.val; }
bool operator!=(flag const& rhs) const { return val != rhs.val; }
bool operator<(flag const& rhs) const { return val < rhs.val; }
T val;
};
typedef flag<int> IntFlag;
typedef flag<double> DoubleFlag;
struct allFlags
{
// Initialize all flags bug flagAD to zero.
allFlags() : flagAD(1) {}
IntFlag flagAA;
IntFlag flagAB;
IntFlag flagAC;
IntFlag flagAD;
IntFlag flagAE;
IntFlag flagZZ;
};
#include <iostream>
int main()
{
allFlags f;
std::cout << f.flagAA << " " << f.flagAD << std::endl;
}
Output:
0 1
You answered your own question quite well:
allFlags flagset3 = {}; // to zero all fields first
flagset3.flagAD = 1;
flagset3.flagAE = 1;
It is clean, and very clear about your intentions. Later, when someone else has to read your code they will understand exactly what you are trying to do.
It is similar to what you see in device driver programming:
registerX = 0 | 1 << BIT2 | 1 << BIT3;
I hope someone can help me. In an effort to be more specific about what I really need, and trim down my code, I have changed from having a vector purely of my Class, to having a vector of objects of a new class, of which my original class is a type within.
I hope I have explained myself clearly up until this point. I will show the relevant classes:
class screen_area
{
private:
int my_id, my_x, my_y, my_width, my_height;
bool active=true;
public:
screen_area (int button_id=0, int x=0, int y=0, int width=0, int height=0, bool isactive=true)
{
my_id = button_id;
my_x = x;
my_y = y;
my_width = width;
my_height = height;
active = isactive;
}
~screen_area()
{}
class bet
{
private:
int wager = 0;
int multiplier = 0;
public:
screen_area area;
bet(int wager, int multiplier, screen_area area)
{};
~bet()
{};
There is a little more to them, but this is the bread and butter. Now previously I had used a member function within "screenarea", to return any value I had wanted from a specific object:
int getvalue(int value)
{
switch(value)
{
case 1 :
return my_id;
case 2 :
return my_x;
case 3 :
return my_y;
case 4 :
return my_width;
case 5 :
return my_height;
case 6 :
return active;
}
}
And I have modified a lookup function to use this member function on the screenarea that is a type contained within "bet".
int returnbuttonid(int mousex, int mousey, std::vector<bet> *buttons)
{
for (auto ep : *buttons )
{
if ((ep.area.getvalue(2) > mousex) && (ep.area.getvalue(3) > mousey))
{int id_value = ep.area.getvalue(1);
return id_value;
}
}
}
However... it returns garbage. I'm clearly missing something, but I am going through it logically and it all seems to make sense.
Sorry in advance if it is something simple! And I appreciate that this may seem long winded but I would really appreciate some help!
And just to be super clear... this is how I am calling it:
vector<bet> localbuttons; //Declaration of Vector
load_map("data.dat", &localbuttons); //load buttonmap using function
int buttonpressed = returnbuttonid(100,300, &localbuttons);
In response to a very speedy comment. It's clear that the problem at least starts with an unpublished piece of code. My vector of "bet" is not being filled with the arguments I am passing to it when I try to overload the constructor. I presumed I had corrected the syntax correctly when I created the new class "bet", but after probing the vector it is not showing any data.
In my function load_map:
bool load_map(std::string path, std::vector<bet> *buttons)
{
//setup file
ifstream inputFile( path.c_str() );
//
//The stuff in the middle here is irrelevant
//and I've take it out to make this tidier
buttons->push_back(bet(0,0, screen_area(id,x,y,width,height, true)));
}
return 0;
}
Now the only part of this that has changed since I had this function was working is:
buttons->push_back(bet(0,0, screen_area(id,x,y,width,height, true)));
So I am guessing this is where the problem originates. The variables are not overloading the default screen_area constructor. So when I:
cout << localbuttons[1].area.my_id << endl;
I always see whatever value I place in the default constructor. It is "0" in the constructor I have posted here, but if I change it, it changes correspondingly.
And I shouldn't have said garbage, I was at fault for thinking I had correctly identified the area of the problem, and trying to be concise. So I guess I should be asking first... How can I correctly overload this "screenarea" constructor?
The problem here was in the Constructor of the Bet class.
After having a look here:
http://www.cplusplus.com/doc/tutorial/classes/
I rewrote the constructor in the Bet class:
bet(int w, int m, int button_id=0, int x=0, int y=0,
int width=0, int height=0, bool isactive=true)
: area(button_id, x, y, width, height, isactive),
wager(w), multiplier(m)
{};
My apologies if I wasted anyone time with misdirection, and thanks for the sensible advice from Jonathon Potter.
I'm not sure why I thought you could call constructors within parentheses. My compiler didn't seem to complain about it, but from what I can gather - I was just creating a temporary object.
Is it possible (albeit probably not good practice) to immediately set values of a struct from a function?
for example :
typedef struct
{
bool success;
std::string returnString;
} functionReturn;
functionReturn go(std::string word[])
{
functionReturn returnStruct;
...
return returnStruct;
}
int main()
{
std::string word[4];
... //assign values to word
std::string returnedString = go(word).returnString //will this work?
}
Is that possible or do I actually have to assign it to another functionReturn and pull out the string value from it?
Yes, that's perfectly possible; it's not different from calling a member function of a returned object, which is quite normal:
std::ostringstream s;
s << "file" << i;
std::ifstream f(s.str().c_str()); //notice calls here
Please don't use the typedef struct {...} name; idiom in C++. This is a holdover from C and has no value in C++. Just use the standard technique: struct name {...};
There is nothing technically wrong with doing what you're doing. Just be careful you don't return a reference to a local, or anything like that. You're not here.
In fact, you could have a method that does something with the parameters and returns a reference to the object, and then chain together method calls, like this:
struct functionReturn
{
functionReturn& doSomething() { return * this; }
functionReturn& doSomethingElse() { return * this; }
};
int main()
{
functionReturn fr;
fr.doSomething().doSomethingElse();
}
This is also valid. It's called method chaining. The question is not weather it's valid, but if it's semantically clear and maintainable. Some people consider constructs like this to be elegant and concise. Others consider it to be an abomination. Count me in the latter group. Decide for yourself.
I have a relatively simple question but I cant seem to find an answer specific for my case and I just may not be approaching this problem the right way. I have a class that looks like this:
struct tileProperties
{
int x;
int y;
};
class LoadMap
{
private:
ALLEGRO_BITMAP *mapToLoad[10][10];
tileProperties *individualMapTile[100];
public:
//Get the struct of tile properties
tileProperties *getMapTiles();
};
I have an implementation that looks like this for the getter function:
tileProperties *LoadMap::getMapTiles()
{
return individualMapTile[0];
}
I have code in the LoadMap class that will assign 100 tile properties for each struct in the array. I want to be able to access this array of structs in my main.cpp file but I just cant seem to find the right syntax or approach. My main.cpp looks like this.
struct TestStruct
{
int x;
int y;
};
int main()
{
LoadMap _loadMap;
TestStruct *_testStruct[100];
//This assignment will not work, is there
//a better way?
_testStruct = _loadMap.getMapTiles();
return 0;
}
I realize that there are many approaches to this, but I'm trying to keep this implementation as private as possible. If someone could please point me in the right direction I would greatly appreciate it. Thank you!
TestStruct *_testStruct;
_testStruct = _loadMap.getMapTiles();
This will get you a pointer to the first element in the array returned. You can then iterate through the other 99.
I would highly recommend using vectors, or another container, and writing getters that don't return pointers to bare arrays like that.
First of all, here, why do we need TestStruct, you can use "tileProperties" structure itself...
And imp thing,
tileProperties *individualMapTile[100]; is array of pointers to the structure.
Hence, individualMapTile will have pointers in it.
You have returned the first pointer, hence you can access the first structure only. What about the others????
tileProperties** LoadMap::getMapTiles()
{
return individualMapTile;
}
int main()
{
LoadMap _loadMap;
tileProperties **_tileProperties;
_tileProperties = _loadMap.getMapTiles();
for (int i=0; i<100;i++)
{
printf("\n%d", (**_tileProperties).x);
_tileProperties;
}
return 0;
}
Use vectors instead of arrays where possible. Also consider an array/vector of TestStruct directly rather than pointers to them. I can't tell if that would be appropriate for you from your code sample.
class LoadMap
{
public:
typedef vector<tileProperties *> MapTileContainer;
LoadMap()
: individualMapTile(100) // size 100
{
// populate vector..
}
//Get the struct of tile properties
const MapTileContainer& getMapTiles() const
{
return individualMapTile;
}
MapTileContainer& getMapTiles()
{
return individualMapTile;
}
private:
MapTileContainer individualMapTile;
};
int main()
{
LoadMap _loadMap;
LoadMap::MapTileContainer& _testStruct = _loadMap.getMapTiles();
}