I am new to C++ (from C# background) and I have a function with the following signature
void AddBenchNode(ref_ptr<Group> root ,ref_ptr<Node> benches, bool setAttitude = false, float scale_x =.15, float scale_y =15, float scale_z = 15, int positionx = 250, int positiony = 100, int positionz =0 )
{
}
But when I try to call the code as below, I get an error which says function does not take 4 arguments.
//then I try to call my function like so
AddBenchNode(root, benches, false, 250);
but I instead get the following error message
error C2660: 'AddBenchNode' : function does not take 3 arguments
Would appreciate an explanation of how C++ does this instead?
Check the prototype in your .hpp file. It's probably declared as
void AddBenchNode(ref_ptr<Group> root ,ref_ptr<Node> benches, bool setAttitude,
float scale_x, float scale_y, float scale_z, int positionx,
int positiony, int positionz);
EDIT: The prototype in the header should be
void AddBenchNode(ref_ptr<Group> root ,ref_ptr<Node> benches, bool setAttitude = false, float scale_x =.15, float scale_y =15, float scale_z = 15, int positionx = 250, int positiony = 100, int positionz =0 );
And your cpp file should then only have
void AddBenchNode(ref_ptr<Group> root ,ref_ptr<Node> benches, bool setAttitude, float scale_x, float scale_y, float scale_z, int positionx, int positiony, int positionz)
{
}
That is, the default parameters are in the prototype, not in the actual definition.
Related
I have a problem with my function. I can't seem to make it return an array of a struct.
Here is the MyApp.h header file:
struct Vertex
{
glm::vec3 p;
glm::vec3 c;
};
class CMyApp
{
public:
CMyApp(void);
~CMyApp(void);
Vertex[] DrawCircle(int cx, int cy);
...
It underlines the DrawCircle and "expects a ';'".
Here is the MyApp.cpp (Of course, header included):
Vertex[] CMyApp::DrawCircle(int cx, int cy) {
Vertex result[42];
result[0] = { glm::vec3((float)cx, (float)cy, 0.0), glm::normalize(glm::vec3(0, 0, 1)) };
for (int ii = 1; ii < 21; ii++) {
float theta = 2.0f * 3.1415926f * float(ii) / float(20);
float x = 0.5 * cosf(theta);
float y = 0.5 * sinf(theta);
result[ii].p = glm::vec3(x, y, 0.0);
result[ii].c = glm::normalize(result[ii].p);
}
result[21] = { glm::vec3((float)cx, (float)cy, 2.0), glm::normalize(glm::vec3(0, 0, 1.0)) };
for (int ii = 22; ii < 42; ii++) {
float theta = 2.0f * 3.1415926f * float(ii) / float(20);
float x = 0.5 * cosf(theta);
float y = 0.5 * sinf(theta);
result[ii].p = glm::vec3(x, y, 2.0);
result[ii].c = glm::normalize(result[ii].p);
}
return result;
}
Same underline here under the function name's DrawCircle for expected ";".
If I remove the array marks then the only error is the return statement. I want to return as an array tho.
Thanks for help in advance.
You cannot return a local array. Such an array is allocated on the stack; when the function returns, all its content is available for other stack variables. If you use it after the call, its content is likely to be corrupted.
So
Vertex[] CMyApp::DrawCircle(int cx, int cy) {
Vertex result[42];
return result;
}
is undefined behavior for the compiler.
You should use a vector instead. Its move constructor makes it efficient for returning many results organized as an array.
std::vector<Vertex> CMyApp::DrawCircle(int cx, int cy) {
std::vector<Vertex> result;
result.reserve(42);
// same content than your original code.
...
return result;
}
Note that if you declare
class CMyApp
{
public:
CMyApp(void);
~CMyApp(void);
typedef Vertex ArrayOfVertices[];
ArrayOfVertices DrawCircle(int cx, int cy);
};
You obtain the error message:
error: ‘DrawCircle’ declared as function returning an array
ArrayOfVertices DrawCircle(int cx, int cy);
I want to return as an array tho.
You can't. C and C++ don't allow it. What you can do in C++ is returning a std::vector which you should use instead of plain arrays anyway.
My code below doesn't compile and can't get it why. Is it because I'm using the newton_raphson_iterate in a wrong way?
Do I need to use binding ? Any examples of how using the newton raphson on a member class function is welcome.
class MyB{
struct funct{
double target;
double DerivativePrecision;
int mo;
bool isG;
MyB* bond;
public:
funct(double target_, double DerivativePrecision_, int mo_, bool isG_, MyB* bond_ ) :
target(target_), DerivativePrecision(DerivativePrecision_), mo(mo_), isG(isG_), bond(bond_)
{}
std::tr1::tuple<double,double> operator()(const double& x) const {
double localYtP = bond->yTp(x, mo, isG);
return std::tr1::make_tuple (
localYtP - target,
(bond->yTp(x+DerivativePrecision,mo, isG)-localYtP)/DerivativePrecision
);
}
};
public:
/*
.....
*/
double yTp(double x, int mo, int isG);
double pty(double p, int mo, int isG){
funct localFunc(p, 0.000001, mo, isG, this);
double y = boost::math::tools::newton_raphson_iterate(localFunc(p),
0.1,
-0.1,
0.4,
std::numeric_limits<double>::digits
);
return y;
}
}
int main()
{
system("pause");
return 0;
}
I get two error messages :
First :
\boost/math/tools/roots.hpp(202) : error C2064: term does not evaluate to a function taking 1 arguments
pointing to the last line of this code (BOOST):
template <class F, class T>
T newton_raphson_iterate(F f, T guess, T min, T max, int digits, boost::uintmax_t& max_iter)
{
BOOST_MATH_STD_USING
T f0(0), f1, last_f0(0);
T result = guess;
T factor = static_cast<T>(ldexp(1.0, 1 - digits));
T delta = 1;
T delta1 = tools::max_value<T>();
T delta2 = tools::max_value<T>();
boost::uintmax_t count(max_iter);
do{
last_f0 = f0;
delta2 = delta1;
delta1 = delta;
boost::math::tie(f0, f1) = f(result);
...
The second :
see reference to function template instantiation 'T boost::math::tools::newton_raphson_iterate<std::tr1::tuple<_Arg0,_Arg1>,double>(F,T,T,T,int)' being compiled
pointing (in my class ) to
double y = boost::math::tools::newton_raphson_iterate(localFunc(p),
0.1,
-0.1,
0.4,
std::numeric_limits<double>::digits
);
The problem is you're calling localFunc when trying to invoke newton_raphson_iterate so end up passing a funct as the first template parameter, which is not callable. You should just pass localFunc directly:
newton_raphson_iterate(localFunc, 0.1, -0.1, 0.4, std::numeric_limits<double>::digits);
I'm getting this error at OpenFrameworks artwork. But appears to be a simple C++ issue.
ofVec2f does not refer to a value
Certainly I'm having problems with pointers, but I could't understand why.
I tried to change & -> *
canvas4.cpp
void Canvas4::createStuff() {
ballCollection.clear();
for (int i=0; i<num; i++) {
ofVec2f org;
org.set(ofRandom(edge, ofGetWidth()-edge), ofRandom(edge, ofGetHeight()-edge));
float radius = ofRandom(50, 150);
ofVec2f loc;
loc.set(org.x+radius, org.y);
float offSet = ofRandom(TWO_PI);
int dir = 1;
float r = ofRandom(1);
if (r>.5) dir =-1;
myBall = new Ball(org, loc, radius, dir, offSet);
ballCollection.push_back(* myBall);
}
//
This is the constructor of Ball class;
Ball::Ball(ofVec2f &_org, ofVec2f &_loc, float _radius, int _dir, float _offSet) {
// **** error occur right here.
// use of undeclared "_org"
org = _org;
loc = _loc;
radius = _radius;
dir = _dir;
offSet = _offSet;
}
Header Canvas4.h
class Ball {
public:
ofVec2f org;
ofVec2f loc;
float sz = 10;
float theta, radius, offSet;
int s, dir, d = 60;
Ball(ofVec2f &_org, ofVec2f &_loc, float _radius, int _dir, float _offSet);
};
class Canvas4{
public:
int fc = 100;
int num = 100;
int edge = 200;
vector<Ball> ballCollection;
Boolean save = false;
ofFbo fbo;
Ball *myBall;
Canvas4();
};
This error is also caused if you call a static method using dot(.) operator instead of scope(::) operator.
OP here - In my case, the error happened due to not closing the method properly, the Canvas::createStuff() was missing "}".
Don't much more without looking at the whole of it, but off the top of my head, C++ compilers will cascade variable names as undeclared if their types are also undeclared, although you may see on out there assuming that the typeless variable is an int, leading to all sorts of goofiness.
Beyond that, check to see if ofVec2 is being included by what you have, and see what namespace it is in. Like, if ofVec2f is in some namespace, you will either need to do using namespacename; or, morepreferrably, refer to ofVec2f with its namespace prefix.
I have a Rectangle class shown below:
Header:
class Rectangle: public Polygon {
private:
float _width, _height;
public:
Rectangle(float width, float height);
float getWidth(float* width) const;
float getHeight(float* height) const;
bool isCollidingWith(Rectangle* other) const;
};
Selected Implementation:
Rectangle::Rectangle(float width, float height) : Polygon(explodeRect(width, height, new struct vertex[4]), 4) {
printf("creating rect %f x %f\n", width, height);
_width = width;
_height = height;
printf("set _width to %f\n", _width);
}
float Rectangle::getWidth(float* width) const {
printf("_w: %f\n", _width);
*width = _width;
return *width;
//return (*width = _width);
}
float Rectangle::getHeight(float* height) const {
return (*height = _height);
}
I initialize an instance of the Rectangle class, and the output indicates that the _width variable is being correctly assigned. However, when I later try to read the variable using the getWidth method, I get an EXC_BAD_ACCESS error on the line:
printf("_w: %f\n", _width);
Why can I no longer read this variable? I get the same problem with the _height variable as well.
EDIT: I would also like to note that if I skip reading the width, I get an error trying to read public variables directly from the object, e.g. when I try to read its x position with obj->x.
EDIT 2: Could this be from the fact that the object is an instance of a subclass of Rectangle, and this subclass is defined in a different file than Rectangle is? I am also reading the values from a third file.
EDIT 3: More code below.
I am trying to re-create Tetris with OpenGL. In my display method, I have this code to draw the rectangles:
if(fallingBlock != nullptr) {
printf("drawing falling block at (%f, %f)\n", fallingBlock->x, fallingBlock->y);
draw(fallingBlock);
}
fallingBlock is defined as a global variable at the top of my file:
Block* fallingBlock;
From my main, I call an initVars method that subsequently calls a startDroppingBlock method. Here it is:
void startDroppingBlock() {
Block* block = availableBlocks[random() % numAvailableBlocks].copy();
block->x = 0.5;
block->y = SCREEN_TOP;
block->dy = -0.01f;
//printf("copied block is at (%f, %f)\n", block->x, block->y);
fallingBlock = block;
}
And here is my block drawing method:
void draw(Block* obj) {
bool shape[3][3];
obj->getShape(shape);
//printf("got shape: {%d, %d, %d}, {%d, %d, %d}, {%d, %d, %d}\n", shape[0][0], shape[0][1], shape[0][2], shape[1][0], shape[1][1], shape[1][2], shape[2][0], shape[2][1], shape[2][2]);
/*float pieceWidth;
obj->getWidth(&pieceWidth);
pieceWidth /= 3.0f;*/
float pieceWidth = obj->getWidth();
for(unsigned int i=0; i<3; i++) {
for(unsigned int j=0; j<3; j++) {
if(shape[i][j]) {
Square rect = Square(pieceWidth);
rect.x = obj->x + pieceWidth * j;
rect.y = obj->y + pieceWidth * i;
rect.color = obj->color;
draw(&rect);
}
}
}
}
I get an EXC_BAD_ACCESS error on the line [...]. Why can I no longer read this variable? I get the same problem with the _height variable as well. [later...] I have tried both float pieceWidth; obj->getWidth(&pieceWidth); and obj->getWidth(new float) - the actual error is on the line where I read _width, before I even use the passed in pointer. [later...] I modified the getWidth and getHeight methods to just simply return _width and _height. Now I just get an error on return _width;
In this case I see you are using a Rectangle* pointer as obj->getWidth which can as well lead to a bad access error if obj is not a valid pointer.
It is to note that I don't quite understand your getter method at all. A simplified (and possibly standard) version of it might be:
float Rectangle::getWidth() const {
return _width;
}
With the only difference that when you used:
// float a;
// float b;
a = rect.getWidth(&b);
you can now do:
// float a;
// float b;
a = b = rect.getWidth();
which is possibly cleaner and will surely don't cause such an error. A good rule of thumb is never to use pointers when possible. If you need to modify a variable inside a function just use a reference.
I'm trying to define a struct in C++ that has properties to return pre-defined values of it's own type.
Like many APIs have for Vectors and Colors like:
Vector.Zero; // Returns a vector with values 0, 0, 0
Color.White; // Returns a Color with values 1, 1, 1, 1 (on scale from 0 to 1)
Vector.Up; // Returns a vector with values 0, 1 , 0 (Y up)
Source: http://msdn.microsoft.com/en-us/library/system.drawing.color.aspx
(MSDN's page of their Color type)
I've been trying to search for hours but I can't for the heart of me even figure out what it's called.
//in h file
struct Vector {
int x,y,z;
static const Vector Zero;
};
// in cpp file
const Vector Vector::Zero = {0,0,0};
Like this?
You can mimic it with static members:
struct Color {
float r, g, b;
Foo(float v_r, float v_g, float v_b):
r(v_r), g(v_g), b(v_b){};
static const Color White;
};
const Color Color::White(1.0f, 1.0f, 1.0f);
// In your own code
Color theColor = Color::White;
This is a static property. Unfortunately, C++ does not have properties of any type. To implement this, you probably want either a static method or a static variable. I would recommend the former.
For the Vector example, you would want something like:
struct Vector {
int _x;
int _y;
int _z;
Vector(int x, int y, int z) {
_x = x;
_y = y;
_z = z;
}
static Vector Zero() {
return Vector(0,0,0);
}
}
You would then write Vector::Zero() to get the zero vector.