I implemented a googletest, with fixture class UnitTest_solver. Implementation for the fixture is the following. It contains helper functions
class UnitTest_solver : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
// setup table with data
m_col = 2;
m_row = 100;
// other things to initialize m_test_data
}
static void TearDownTestCase()
{
for(int i = 0 ; i < m_row ; i++)
delete[] m_test_data[i];
delete[] m_test_data;
}
static double chi_sqr(double* x)
{
if(m_col < 2)
return 0;
double fx = 0;
double * row_i = new double[m_col - 1];
for(int i = 0 ; i < m_row ; i++)
{
for(int j = 0 ; j < m_col - 1 ; j++)
row_i[j] = m_test_data[i][j];
fx += pow(m_test_data[i][0] - func_1(x, row_i, m_col - 1), 2.0);
}
return fx;
}
static double func_1(double* x, double* dbl, int nb_param)
{
if(nb_param != 2)
return 0;
return x[0] * exp(-1 * x[1] * dbl[0]);
}
static double UnitTest_solver::functPtr( double * parameters, void * userinfo)
{
return chi_sqr(parameters);
}
static ofstream thing;
static double** m_test_data;
static int m_col, m_row;
};
Also, out of the fixture scope, i initialize static variables. Last is function pointer. is definition syntax ok ?
double** UnitTest_solver::m_test_data = 0;
int UnitTest_solver::m_col = 0;
int UnitTest_solver::m_row = 0;
double (UnitTest_solver::*functPtr)(double * , void *) = 0;
then, i have a test case, with link to fixture UnitTest_solver.
TEST_F(UnitTest_solver, testFunc1)
{
Solver* solversqp = new Solver();
solversqp->set_pointer_to_function(UnitTest_solver::functPtr, (void*)0);
//...
}
second line show compile time error with UnitTest_solver::functPtr : when mouse is over the error, info is 'function defined at line xxx is unacessible', with xxx pointing to functPtr definition inside the fixture.
If i run the ggltest commenting the last line, solversqp->set_pointer_to_function(UnitTest_solver::functPtr, (void*)0);, test is finishing (if i put a trivial ASSERT, it is successful).
Whats wrong with my function pointer definition.
I do not see full code, therefore this is just a guess.
Everything in class UnitTest_solver is protected, therefore everything (other then classes inheriting for this class) do not have access to it's members. Change it to public, and your problem will be solved :
class UnitTest_solver : public ::testing::Test
{
// protected:
public:
Related
Consider 2 variables (number of polygons and its coordinates) :
int numberPoly= 2;
float polycoord[18]= {0,50,0,0,0,0,50,0,0,0,50,0,50,50,0,50,0,0};
, a Model class (that is intended to store polygon classes to a list) :
class model{
public:
model();
void affect(int id, int address){
polyclasses[id]=address;
}
private:
string name;
vector<int> polyclasses;
};
, a Polygon class (that I have to sort in Model's polyclasses list) :
class polygone {
public:
polygone();
void affect(int id, int coord){
ABC[id]=coord;
}
private:
int id;
float ABC[9]={0.0};
};
I wanted to code a function (cf. "builder") that instanciate n Polygon classes and sort them (with their memory addresses like an id) in an array ("polyclasses" from Model class). So, I don't arrive. Here is a bit of my builder function not acomplished :
void builder(){
int from = 0; int subfrom = 0;
for(int i=0; i < numberPoly - 1; i++){
from = 0; subfrom = 0;
polygone poly();
!!! need to put that instance in Model's polygon list !!!
...
for(int j=from; j < (polycoord.size())-1; j++){
poly.affect(subfrom, polycoord[j]) ...
subfrom++;
}
from += 3;
}
}
This is for my first c++ project. I'm coding a light 2d engine.
You need to store pointer of instances in your vector and allocate your objects with new keyword. At destructor of your model yo uwill need to deletethe object to avoid a memory leak.
// Model.h
// Class name should begin with uppercase by convention
class Model{
public:
Model();
~Model();
void builder();
// Implementation should go in cpp file
void affect(int id, int address);
private:
// Having a m_ prefix on private variable is useful to make your code more readable so a reader can easily know if a variable is private or not
string m_name;
vector<Polygon*> m_polyclasses;
};
// Polygone.h
class Polygone {
public:
Polygone();
// Don't forget destructor
~Polygone();
// Implementation should go in cpp file
void affect(int id, int address);
private:
int m_id;
// Use std::array in C++ and give meaningful name to your variable
// float m_ABC[9]={0.0}; is replaced by :
std::array<float, 9> m_coordinates;
};
// Model.cpp
void Model::builder() {
int from = 0; int subfrom = 0;
for(int i=0; i < numberPoly - 1; i++){
from = 0; subfrom = 0;
Polygone * poly = new Polygone();
// A pointer of poly is now stored in Model
this->polyclasses.push_back(poly);
// Your polygone object should initialized in the constructor or in a member function of the class Polygone.
for(int j=from; j < (polycoord.size())-1; j++){
poly->affect(subfrom, polycoord[j]) ...
subfrom++;
}
from += 3;
}
}
Model::~Model() {
for(auto p: this->polyclasses) {
// Avoid memory leak
delete p;
}
this->polyclasses.clear();
}
You can also store a std::unique_ptr instead of a plain pointer. In that case you don't need to delete.
I need to avoid(mock) unit testing of line of code displaying messagebox using FakeItEasy framework.
Code is here,
public class XYZ
{
public static int nValue = 0;
public void AddInetegers(int i)
{
int j = i * 100;
int k = j * 30 / 100;
MessageBox.Show("Value Here {0}", k.ToString());
nValue = k;
}
}
MessageBox.Show is a static member, and cannot be faked by FakeItEasy. In these situations, typically the code that accesses the non-fakeable service is isolated and wrapped in an interface.
Here's how I would do it:
interface IAlerter
{
void Alert(string text, string caption);
}
public class XYZ
{
public static int nValue = 0;
private readonly IAlerter _alerter;
public XYZ(IAlerter alerter)
{
_alerter = alerter;
}
public void AddInetegers(int i)
{
int j = i * 100;
int k = j * 30 / 100;
_alerter.Show("Value Here {0}", k.ToString());
nValue = k;
}
}
[TestMethod]
public void Test_Using_FakeItEasy()
{
var alerter = A.Fake<IAlerter>();
// No need to configure alerter.Alert(), since it doesn't return a value
var xyz = new XYZ(alerter);
xyz.AddInetegers(3);
Assert.AreEqual(90, XYZ.nValue);
}
I have a class that contains a variable 'beta'. I want to run the code with 1000 different values of 'beta' that range between 0 and 1. My first thought was to run a loop but I am unable to do this within a class. I also have tried using pointers but this did not seem to work. I apologise if my question is rather amateur but I am a Math grad, not computer science. Can someone please help!
The code for my class is listed below.
class FalknerSkan : public MFunction
{
public:
//constuctor to initialise kappa
FalknerSkan() {beta = 0.0;}
MVector operator()(const double& x, const MVector& y)
{//y[0]=f, y[1]=f', y[2]=f'', y[3]=Z1, y[4]=Z2, y[5]=Z3
MVector temp(6);
temp[0] = y[1];
temp[1] = y[2];
temp[2] = -y[0]*y[2] - beta*(1-y[1]*y[1]);
temp[3] = y[4];
temp[4] = y[5];
temp[5] = -y[2]*y[3] + 2.0*beta*y[1]*y[4] - y[0]*y[5];
return temp;
}
void SetKappa(double k) {beta = k;} //change kappa
private:
double beta; // class member variable, accessible within
//all FalknerSkan member functions
};
Thank you
This is a loop inside a class.
#include <iostream>
class Foo
{
public:
Foo() : beta(0.0)
{}
void print(){
for (int i(0); i < 1000; ++i)
std::cout << ++beta << std::endl;
}
private:
double beta;
};
int main()
{
Foo obj;
obj.print();
return 0;
}
In C++ I have an array of doubles which need initialising programmatically, at run time, just once, for the whole class to share. They could be both static and constant. How best can I initialise them? I have gone off using static with the prodigious popularity of parrallel processors presently pervading. So must I set a flag to run once or is there some static const magic which will initialise them as a variable local to a function (ok) or class (ok too)?
double sumOfWeights = 0.0;
double fracObs = 0.0;
for (int i = 0; i < NUMTRACES; i++) {
double weightAtI = SQUARED(1 - SQUARED(MAXTRACEWRTMIDTRACE * (MIDTRACE - i)
/ double(MIDTRACE)));
sumOfWeights += weightAtI;
fracObs += obsArray[i] * weightAtI;
}
return fracObs / sumOfWeights;
In the code above I'd like to make weightAtI a lookup with each double already divided by sumOfWeights so I can retrieve them without iterating through NUMTRACES.
_EDIT_
It's okay, that's what constructors are for :)
Just hoping to tackle my static, const and initialization gremlins into the bargain. Thanks Seth
_EDIT_
Not sure it is quite the effect I wanted though. The constructor runs on each instance, even if the members are static, no? No. Lemme see...
_EDIT_
I think the most efficient solution, is to guard the initializer loop with a static flag, in the constructor. Being a POD flag I'm sure it should behave appropriately, I'm just not quite sure what that is at this stage.
_EDIT_
Ahh, got it:
class X
{
public:
static int i;
};
int X::i = 0; // definition outside class declaration
_EDIT_
Unfortunately, when it comes to my code,
static const int MIDTRACE = 3;
static const int NUMTRACES = 2 * MIDTRACE + 1;
static double WEIGHTATI[NUMTRACES];
I get linker errors:
meobj.obj : error LNK2020: unresolved token (0A00001C) "private: static double * mens:meclass::PIMPL::WEIGHTATI" (?WEIGHTATI#PIMPL#meclass#mens##$$Q0PANA)
meobj.obj : error LNK2001: unresolved external symbol "private: static double * mens:meclass::PIMPL::WEIGHTATI" (?WEIGHTATI#PIMPL#meclass#mens##$$Q0PANA)
due to my constructor:
meclass::PIMPL() {
if (!doneStaticInit) {
double sumOfWeights = 0.0;
for (int i = 0; i < NUMTRACES; i++) {
WEIGHTATI[i] = SQUARED(1 - SQUARED(MAXTRACEWRTMIDTRACE * (MIDTRACE - i) / double(MIDTRACE)));
sumOfWeights += WEIGHTATI[i];
}
for (int i = 0; i < NUMTRACES; i++) WEIGHTATI[i] /= sumOfWeights;
doneStaticInit = true;
}
}
Initialization => constructor. Once => static instance. So one way is static instance of something with constructor.
#include <iostream>
struct Foo
{
Foo()
{
std::cout << "Initializing them values..." << std::endl;
for( int i = 0; i < 3; ++i )
{
values[i] = i;
}
};
int values[3];
};
void doThings()
{
static Foo const foo; // Is initialized ONCE.
for( int i = 0; i < 3; ++i )
{
std::cout << foo.values[i] << " ";
}
std::cout << std::endl;
}
int main()
{
doThings();
doThings();
doThings();
}
Cheers & hth.,
You can put a static bool flag in your constructor. The flag will only be initialized to false the first time it is called. After that it will remain true.
// foo.h
class Foo {
static const int MIDTRACE = 3; // static const, no definition needed
static const int NUMTRACES = 2 * MIDTRACE + 1; // static const, no definition needed
static double WEIGHTATI[NUMTRACES]; // not const, so need definition outside of class
public:
Foo() {
static bool array_initialized = false;
if( !array_initialized ) {
// Initialize array
array_initialized = true;
}
}
// Other members
};
In a source file, not header file:
// foo.cpp
include "foo.h"
double Foo::WEIGHTATI[NUMTRACES];
I have made a class and it compiles with no syntax errors, but I get 6 unresolved external symbols?
THE CLASS:
struct CELL {
private:
static bool haslife;
static int x;
static int y;
public:
static bool has_life()
{
return haslife;
}
static void set_coords(int xcoord, int ycoord)
{
x = xcoord;
y = ycoord;
}
static void get_coords(int &xcoord, int &ycoord)
{
xcoord = x;
ycoord = y;
}
};
class cell_grid {
private:
static int cell_size;
static int cell_count_x;
static int cell_count_y;
CELL **cell;
public:
cell_grid();
cell_grid(unsigned int width,unsigned int height, unsigned int cellsize)
{
//set size based on cellsize
this->cell_size = cellsize;
this->cell_count_x = floor((double)width / this->cell_size);
this->cell_count_y = floor((double)height / this->cell_size);
this->cell = new CELL*[this->cell_count_y];
for(int i = 0; i < this->cell_count_y; i++)
{
cell[i] = new CELL[this->cell_count_x];
}
for(int y = 0; y < this->cell_count_y; ++y)
{
for(int x = 0; x < this->cell_count_x; ++x)
{
int cur_x = x * this->cell_size;
int cur_y = y * this->cell_size;
this->cell[x][y].set_coords(cur_x,cur_y);
}
}
} //end of constructor
static int get_cell_size()
{
return cell_size;
}
static void render(BITMAP *buff)
{
circlefill(buff,70,70,60,makecol(27,37,0));
}
};
MAIN
int main()
{
start_allegro();
cell_grid *grid = new cell_grid(scr_w,scr_h,10);
grid->render(buffer);
//Main Loop
while (!done && !key[KEY_ESC]) //until 'X' pressed or ESC
{
//***** Start Main Code Here *****
while (speed_counter > 0)
{
//render the buffer to the screen
blit(
buffer,
screen,
0,0,0,0,
scr_w,
scr_h);
clear_bitmap(buffer);
speed_counter --;
}
//***** End Main Code Here *****
rest(1); //Normalize cpu usage
}
return 0;
}
END_OF_MAIN()
Thanks
Don't define all of the class variables as static.
When you define a data member as static it means there is only one single instance of it. This doesn't seem to be what you want to do here.
Instead of
private:
static bool haslife;
static int x;
static int y;
write:
private:
bool haslife;
int x;
int y;
Further more, when you define a static member, you need to define it again in the CPP file and initialize it with a value. It doesn't look like you're doing that and that's why you're getting the linker errors.
Also, next time you post something, make sure you actually ask a question rather than just simply stating facts.