I'm trying to initialise static pointers as arrays inside a class definition, but getting runtime errors. I've seen examples where something similar is done, but I can't get it working, and not sure why. Some example code I've tried is:
class Header
{
private:
static int *pointer;
public:
int getVal(int val);
};
Class definition:
#include "Header.h"
int* Header::pointer = new int[] {0, 1, 2, 3, 4};
int Header::getVal(int val)
{
return pointer[val];
}
main:
#include "Header.h"
#include <iostream>
int main(int argc, char ** argv)
{
Header header;
for (int i = 0; i < 5; i++)
{
std::cout << header.getVal(i);
}
}
Running this causes an error while initialising the pointer. If I run through it in the debugger, and ignore the error, I can see that the pointer is initisalised with 0 at the beginning. If I then continue to step through it I get another error saying the heap's been corrupted. Is it possible to intitialise a pointer in this way? If not, are there any suggestions on how one can initialise a member variable pointer into an array, and assign it values, inside the class definition without having to assign each element of the array individually.
You could probably get away with:
class Header
{
public:
int getVal(int valIndex);
};
and then
#include "Header.h"
static int s_vals[] = {0, 1, 2, 3, 4}; // could move this line to B
int Header::getVal(int valIndex)
{
// B
return s_vals[valIndex];
}
Considering that you know the size of the array at compile time and there is no need to advertise an implementation detail if you are providing accessors anyway.
it is possible that your compiler simply does not support braced-init-list.
If so you can rewrite your class the following way
class Header
{
private:
static int *pointer;
static int *init()
{
int *p = new int[5];
std::iota( p, p + 5, 0 );
return ( p );
}
public:
int getVal(int val);
};
And then pointer is defined the following way
int * Header::pointer = Header::init();
Related
Here's the code:
#include <iostream>
using namespace std;
class Zaix
{
private:
static int mor;
public:
static int beri;
static void setmor(int lip)
{
Zaix::mor=lip;
}
static int getmor(void)
{
return mor;
}
};
int Zaix::beri=3;
int main()
{
cout<<Zaix::beri<<endl;
Zaix::beri++;
cout<<Zaix::beri<<endl;
Zaix::setmor(6);
return 0;
}
Now, line 4 of main() function Zaix::setmor(6); somehow invalidates line 11 of the code presented Zaix::mor=lip;. With this line commented out, the whole thing compiles OK, with it present, compiler gives this error:
undefined reference to Zaix::mor"
Any idea why that is?
Define the variable outside class as well.
int Zaix::mor;
For assignment:
int Zaix::mor = 4;
In C++ we need to define all the static member variable of a class outside of it else we get a linking error. You just need to do like below:-
int Zaix::mor;// Just add this line below int Zaix::beri = 3;
im new in c++ (and not to old in programming...) and i have problem with handling vectors and strucs in class.
basically i have a vector and a array of pointers to struct members in the class and i want work on the in my methos but im doing something worng/
here is my movement.h
#pragma once
using namespace std;
class movement
{
private:
static const int MAX_ROW_PER_TRACKER = 100;
static const int MIN_TO_START_CALC = 30;
static const int MAX_TRACKERS = 20;
struct tracker
{
int id;
double a[MAX_ROW_PER_TRACKER];
double b[MAX_ROW_PER_TRACKER];
double c;
};
vector<int> trackersOrder[MAX_TRACKERS] = {};
tracker* trackersArr[MAX_TRACKERS];
public:
movement();
void addRow(int a, int b, int c);
~movement();
};
and my movement.cpp
#include "stdafx.h"
#include "movement.h"
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
movement::movement()
{
}
void movement::addRow(int id, int a, int b)
{
int index;
vector<int>::iterator searchID = find(trackersOrder.begin(), trackersOrder.end(), ID);
if (searchID == trackersOrder.end())
{
vector<int>::iterator freeLocation = find(trackersOrder.begin(), trackersOrder.end(), 0);
index = freeLocation - trackersOrder.begin();
trackersOrder.insert(trackersOrder.begin + index, id);
structArr[index] = new tracker;
structArr[index]->id = id;
structArr[index]->a[0] = a;
structArr[index]->b[0] = b;
structArr[index]->c = 0;
}
}
movement::~movement()
{
}
so when i send to method "addRow" id, and b i want to first check if i allready have this id in my vector (the vector just give me the index for the structs array) and if not then if put the id in the first empty place in the vector and on the structs array/
but from some reasin its look to me that the methid dont reconized the vector and the structs. can you help me understand why?
p.s - i can bet that i have more mistakes in my code, its my firs try with pointers and ect. (im comming from the good life in Matlab) so i will be happy to learn on them also
thank you very much!
The main problem
The problem is that in your code, trackersOrder is not a vector but an array of vectors:
vector<int> trackersOrder[MAX_TRACKERS] = {}; // array of MAXTRACKERS vectors !!
The solution
If you define it as simple vector, it should work better:
vector<int> trackersOrder;
If you want to set its size do it in the movement constructor:
movement::movement() : trackersOrder(MAX_TRACKERS)
{
}
Other issues
There is a case typo with an ID that should be id.
auto searchID = find(trackersOrder.begin(), trackersOrder.end(), id); // by the way auto is easier + ID corrected
There are a missing () after a begin whicn transforms unfortunately your iterator arithmetic into function pointer arithmetic (sic!!):
trackersOrder.insert(trackersOrder.begin() + index, id); // corrected
Finally, there are a couple of structArr that should be replaced by trackersArr.
The result does finally compile (online demo)
I'm changing the class implementation of a large class for a company project that has several static variables declared as private members of the class. There are many arrays and structs declared in the class header that utilize these static variables. I now need to assign the static data members values from my main function somehow. I tried assigning the static variables through the constructor but the header is declared prior to the constructor call so that wasn't possible.
For example, if I have
class Data
{
private:
static unsigned int numReadings = 10;
static unsigned int numMeters = 4;
unsigned int array[numMeters];
}
I would want to change it such that I could set numReadings and numMeters from my main function somehow, so it will allow all of my arrays and structs that utilize numMeters and numReadings to be initialized properly.
Is there a way to do this in C++? Of course I could always change my class design and set these in the constructor somehow but I'd like to avoid that if I can as it will take quite a long time.
You cannot do it in the main function, but you can do it in the main.cpp file:
// Main.cpp
#include <iostream>
#include "T.h"
using namespace std;
int T::a = 0xff;
int main()
{
T t; // Prints 255
return 0;
}
// T.h
#pragma once
#include <iostream>
using namespace std;
class T {
public:
T() { cout << a << endl; }
private:
static int a;
};
Have you tried making them public and accessing them with Data::numReadings = 10?
UPDATE:
#include <cstdlib>
using namespace std;
/* * */
class Asdf
{
public:
static int a;
};
int Asdf::a = 0;
int main(int argc, char** argv) {
Asdf::a = 2;
return 0;
}
Regardless of the accessibility of these variables, you need to define and initialize the static members outside the class definition:
// header
class Data
{
private:
static unsigned int numReadings;
static unsigned int numMeters;
unsigned int array[numMeters]; //<=see edit
};
// class implementation file
unsigned int Data::numReadings = 10;
unsigned int Data::numMeters = 4;
This is part of the implementation of the class and shouldn't be in the header (ODR rule).
Of course, if you want to access these variables (which are shared among all instances of the class) from outside, you need to make them public, or better, foresee and accessor.
Edit:
As the question is formulated around the static issue, I didn't notice the variable length array : this is not standard c++, although some compilers might accept it as a non-standard extension.
To do this properly, you should define a vector and initialize it at construction:
class Data
{
public:
Data ();
private:
static unsigned int numReadings;
static unsigned int numMeters;
vector<unsigned int> mycontainer; //<=for dynamic size
};
Data::Data() : mycontainer(numMeters) { } // initialize object with right size
I want to declare a pointer in my .h and initialize it in .cpp. For example an int pointer:
My .h class file:
#pragma once
#include <iostream>
#include <stdio.h>
#include <stdint.h>
using namespace std;
class Calc_ToF_low
{
private:
int telo[3];
public:
Calc_ToF_low(void);
~Calc_ToF_low(void);
double * CalcToF(int16_t * señal, int fs);
long double * filter(long double *ganancias, long double *coeficientes, double *señal,int lensignal, int L, int control);
void signal_p1_lowf(void);
void avg_p1_lowf(void);
void time_est();
};
My .cpp class file:
#include "Calc_ToF_low.h"
Calc_ToF_low::Calc_ToF_low(void)
{
telo[3]={0,1,2};
}
How can I do this?
Like this:
Calc_ToF_low::Calc_ToF_low() // note no need to say void in C++
{
telo[0]=0;
telo[1]=1;
telo[2]=2;
}
Or if you can use C++11, something like this might work:
Calc_ToF_low::Calc_ToF_low()
: telo{{0,1,2}} // initializer list, will not work in "old" C++98
{}
You could just assign values to it by typing:
telo[0] = 0;
telo[1] = 1;
telo[2] = 2;
in your .cpp.
It may not be perfect for huge arrays but then you probably should assign the values from a file instead.
If you're initializing large arrays with a constant value for all item, you can use this approach:
Calc_ToF_low::Calc_ToF_low(){
memset(telo, 0, sizeof(telo)); //0 is the constant value
}
If you want to initialize your large array to some set of values that has no patterns:
int defaultTeloData[TELO_NUMITEM] = {2,4,1,5,6,1,7,82,41,6,134,88,1};
Calc_ToF_low::Calc_ToF_low(){
memcpy(telo, defaultTeloData, sizeof(telo));
}
If your array values has pattern, use a loop and some formulas or constructors.
Calc_ToF_low::Calc_ToF_low(){
for(int a = 0; a sizeof(telo)/sizeof(telo[0]); a++){
telo[a] = dataFormulaForTelo(a);
}
}
This is one way you could do it:
#include <array>
class Calc_ToF_low
{
private:
std::array<int, 3> telo;
public:
Calc_ToF_low();
};
Calc_ToF_low::Calc_ToF_low()
: telo()
{
for(unsigned i = 0; i<telo.size(); ++i)
telo[i] = i;
}
this is my first post on SO, even though i've spent some time already here.
I've got here a problem with a function returning a 2d array. I have defined a private 2d int array property int board[6][7] in my Game class, but i don't know how to create a public getter for this property.
These are relevant parts of my game.h:
#ifndef GAME_H
#define GAME_H
class Game
{
public:
static int const m_rows = 6;
static int const m_cols = 7;
Game();
int **getBoard();
private:
int m_board[m_rows][m_cols];
};
#endif // GAME_H
Now what I would like is something like this in game.cpp (cause I thought array name without brackets is a pointer to first element, obviously it doesn't work with 2d arrays) :
int **Game::getBoard()
{
return m_board;
}
So that i can put this for example in my main.cpp:
Game *game = new Game;
int board[Game::m_rows][Game::m_cols] = game->getBoard();
Can anybody help me, what should i put in my game.cpp ?
Thanks!
You cannot pass arrays by value into and out of functions. But there's various options.
(1) Use a std::array<type, size>
#include <array>
typedef std::array<int, m_cols> row_type;
typedef std::array<row_type, m_rows> array_type;
array_type& getBoard() {return m_board;}
const array_type& getBoard() const {return m_board;}
private:
array_type m_board;
(2) Use the correct pointer type.
int *getBoard() {return m_board;}
const int *getBoard() const {return m_board;}
private:
int m_board[m_rows][m_cols];
An int[][] has no pointers involved. It isn't a pointer to an array of pointers to arrays of integers, it's an array of an array of integers.
//row 1 //row2
[[int][int][int][int]][[int][int][int][int]]
Which means one int* points to all of them. To get to a row offset, you'd do something like this:
int& array_offset(int* array, int numcols, int rowoffset, int coloffset)
{return array[numcols*rowoffset+coloffset];}
int& offset2_3 = array_offset(obj.getBoard(), obj.m_cols, 2, 3);