I have a code::blocks project, called Test.cbp. It has three files, main.cpp in the Test directory, and jAlg.cpp and jAlg.h, both in the jAlg directory.
main.cpp
#include <iostream>
#include "jAlg.h"
int main(){
jVector bob;
jMatrix ann;
bob.display();
return 0;
}
jAlg.cpp (summary)
class jMatrix{
public:
//The four entries of a 2x2 square matrix:
//[a b]
//[c d]
double a, b, c, d;
//Constructor
jMatrix(double a_val = 1, double b_val = 0,
double c_val = 0, double d_val = 1){
a = a_val;
b = b_val;
c = c_val;
d = d_val;
}
//Several other functions and operator overloads
};
class jVector{
public:
//The two entries of a 2D vector
//[x]
//[y]
double x, y;
//Constructor
jVector(double x_val = 0,
double y_val = 0){
x = x_val;
y = y_val;
}
//Several other functions and operator overloads
};
//Several other functions
//Matrix-vector multiplication
jVector operator* (jMatrix A, jVector v){
jVector result;
result.x = A.a*v.x + A.b*v.y;
result.y = A.c*v.x + A.d*v.y;
return result;
}
//More functions
jAlg.h (summary)
#ifndef JALG
#define JALG
double sqr(double x);
class jMatrix{
public:
double a, b, c, d;
jMatrix(double a_val = 1, double b_val = 0,
double c_val = 0, double d_val = 1);
//more functions
};
class jVector{
public:
double x, y;
jVector(double x_val = 0, double y_val = 0);
//more functions
};
jVector operator* (jMatrix A, jVector v);
#endif
When I build and run the project, it behaves strangely. An error is raised saying undefined reference to 'jMatrix::jMatrix(double,double,double,double)'. However, there is no error related to the jVector::jVector constructor.
As a test I went to the jAlg files and commented out the jVector operator* (jMatrix A, jVector v) function and run the project again. This time, an error is raised for both jMatrix::jMatrix and jVector::jVector. For some reason, the presence of that function makes it okay to define vectors, but not matrices.
So here's my question: why does the presence of the function jVector operator* (jMatrix A, jVector v) make it okay to define jVectors? What can I do to make it possible to define jMatrix objects?
In your jAlg.cpp file, you should only define your functions, don't declare everything again
jMatrix::jMatrix(double a_val, double b_val, double c_val, double d_val)
: a{a_val}, b{b_val}, c{c_val}, d{d_val}
{ }
// ... define other jMatrix functions similarly
jVector::jVector(double x_val, double y_val)
: x{x_val}, y{y_val}
{ }
// ... define other jVector functions
//Several other functions
jVector operator* (jMatrix A, jVector v)
{
jVector result;
result.x = A.a*v.x + A.b*v.y;
result.y = A.c*v.x + A.d*v.y;
return result;
}
In your jAlg.cpp file you shouldn't redeclare your class, but just put definitions for the functions declared from jAlg.h (do so for the other class member functions analogous):
jMatrix::jMatrix(double a_val, double b_val,
// ^^^^^^^^^ Prefix class scope
double c_val, double d_val)
: a(a_val), b(b_val), c(c_val), d(d_val) {}
Also use the member initializer list (as shown above).
The definition of the free function jVector operator* (jMatrix A, jVector v); is OK.
Related
I'm new to C++ but I have a good programming background and I have been looking for function calls that don't need a reference object to a struct or class. The best referral to what I'm looking for is probably any of unity's classes where for instance Vector2.Distance can be used and it returns another Vector2 but Vector2 is the class!
#include <stdio.h>
#include <stdlib.h>
struct vector {
float x, y;
// only recently figured out you could do this
// instead of vector() {x = 0.0; y = 0.0} etc.
vector() : x(0.0), y(0.0) {}
vector(float _x, float _y) : x(_x), y(_y) {}
vector add(vector a, vector b) {
return vector(this->x + b.x, this->y + b.y);
}
};
int main() {
vector a = vector(2, 3);
vector b = vector(4, 4);
vector c = vector.add(a, b);
printf("%f, %f", c.x, c.y);
return 0;
}
// expected output from this function: 6, 7
The code above is an example of what I am wanting, so the reasoning behind what is happening is redundant, I know there is a vector class and I'm sure there is a much simpler way of doing this code in particular but this is the root functionality of what I want.
is this even possible in this language?
int main() {
vector a = vector(2, 3);
vector b = vector(4, 4);
this works: vector c = a.add(a, b);
this !works: vector c = vector.add(a, b);
printf("%f, %f", c.x, c.y);
return 0;
}
I am aware that this works but all im trying to do is get rid of needing the A reference in a.add();
I've tried static functions, looking into the std::functional thing, operation overloading but I might have misinterpreted something and came across a solution
Thanks in advance!
You can define static functions inside your classes.
#include <stdio.h>
#include <stdlib.h>
struct vector {
float x, y;
// only recently figured out you could do this
// instead of vector() {x = 0.0; y = 0.0} etc.
vector() : x(0.0), y(0.0) {}
vector(float _x, float _y) : x(_x), y(_y) {}
// add "static"
static vector add(vector a, vector b) {
return vector(a.x + b.x, a.y + b.y); // use correct object
}
};
int main() {
vector a = vector(2, 3);
vector b = vector(4, 4);
vector c = vector::add(a, b); // use :: instead of .
printf("%f, %f", c.x, c.y);
return 0;
}
I have a function my_func(), which takes 2 parameters a and b.
I want to define a function inside the solve_for_b_by_bisection() function, called f, such that I can just call f(b), which is my_func(a, b) for some fixed input a. How do I do that? Do I use a function pointer?
The reason I am doing this instead of calling f(a,b) directly is that in the actual thing I am working on, it has 10+ variables which are constants - it is not possible to repeat the variable list every time.
double my_func(const double a, const double b)
{
/* some arbitary function */
}
double solve_for_b_for_contant_a_by_bisection (const double a,
const double upperbound,
const double lowerbound)
{
double (*my_func_pointer)(const double b)
{
&my_func(a, b)
}
lowerboundvalue = *my_func(lowerbound)
upperboundvalue = *my_func(upperbound)
midpointvalue = *my_func(0.5 * (lowerbound+upperbound))
/* The rest of the implementation */
}
You might use lambda:
auto func = [a](double b) { return my_func(a, b); };
Just use lambda:
double solve_for_b_for_contant_a_by_bisection (const double a,
const double upperbound,
const double lowerbound)
{
auto f = [a]( double b ) { return my_func( a, b ); };
auto lowerboundvalue = f(lowerbound)
auto upperboundvalue = f(upperbound)
auto midpointvalue = f(0.5 * (lowerbound+upperbound));
/* The rest of the implementation */
}
You could either use a lambda function, as others have suggested, or std::bind. See how that will look and whether you like it better:
#include <functional>
double my_func(const double a, const double b)
{
/* some arbitary function */
}
double solve_for_b_for_contant_a_by_bisection (const double a,
const double upperbound,
const double lowerbound)
{
const auto f = std::bind(my_func, a, std::placeholders::_1);
const auto lowerboundvalue = f(lowerbound);
const auto upperboundvalue = f(upperbound);
const auto midpointvalue = f(0.5 * (lowerbound+upperbound));
/* The rest of the implementation */
}
Suppose the "standard" C++ inheritance paradigm:
struct GeneralFunc
{
/*..members..*/
virtual double value(double a, double b) { return 0; }
};
struct Func_classA : GeneralFunc
{
/*..members..*/
double value(double a, double b) { return a * b; }
};
struct Func_classB : GeneralFunc
{
/*..members..*/
double value(double a, double b) { return a + b; }
};
void main(){
double a = 1.0, b = 1.0;
std::vector<GeneralFunc*> my_functions;
//fill my_functions from input
for (auto& f : my_functions)
{
double v = f->value(a, b);
}
}
I would like an implementation that is most efficient for the iteration, i.e. minimizes indirect references, maximizes inline optimizations, ect. To constrain the problem, I know beforehand each specific "type" I want to implement (I can define only the "func" types I require, without having to allow other possibilities).
several options appear available:
boost::polycollection
#include <boost/poly_collection/base_collection.hpp>
//...rest the same
boost::base_collection<GeneralFunc> my_functions
//...rest the same
std::variant
#include <variant>
//...rts
using funcs = std::variant<Func_classA, Func_classB /*..possibly more../*>
std::vector<funcs> my_functions
or CRTP (Curiously Recurring Template Pattern)
Let me know the correct nomenclature for this, but here I "upcast" the base class based on the "type" -- a kind of manual dispatch.
template<typename T>
struct GeneralFunc
{
/*..members..*/
int my_type;
double value(double a, double b) {
switch (my_type){
case TYPE_A:
return static_cast<Func_classA*>(this)->value(a,b);
/*..you get the idea..*/
I'm okay sacrificing marginal efficiency for ease of development, but is there a consensus on the "best practice" in this case?
EDITS* fixed some typos; my current development is "in-development" of CRTP the last option.
SOLUTION:
After testing, both boost::polycollection and std::variant are valid approaches. However, this turned out to be far most efficient (from memory, may be slightly off).
enum ftype { A = 0, B, C };
struct GeneralFunc
{
ftype my_type;
GeneralFunc(ftype t) : my_type(t) {}
inline double value(double a, double b) const; // delay definition until derived classes are defined
}
struct Func_classA : GeneralFunc
{
Func_classA() : GeneralFunc(ftype::A) {}
inline double value(double a, double b) const { return a * b; }
}
/* define B, C (& whatever) */
inline double GeneralFunc::value(double a, double b)
{
switch(my_type){
case (ftype::A):
return static_cast<Func_classA*>(this)->value(a,b);
/* same pattern for B, C, ect */
}
}
void main(){
std::vector<std::unique_ptr<GeneralFunc>> funcs;
funcs.push_back(std::make_unique<Func_classA>());
funcs.push_back(std::make_unique<Func_classB>());
funcs[0]->value(1.0,1.0); // calls Func_classA.value
funcs[1]->value(1.0,1.0); // calls Func_classB.value
}
I'd be tempted to just use std::function as the container, rather than re-writing it.
using GeneralFunc = std::function<double(double, double);
struct Func_classA
{
/*..members..*/
double value(double a, double b) { return a * b; }
/*explicit*/ operator GeneralFunc () const { return [this](double a, double b){ value(a, b) }; }
};
struct Func_classB
{
/*..members..*/
double value(double a, double b) { return a + b; }
/*explicit*/ operator GeneralFunc () const { return [this](double a, double b){ value(a, b) }; }
};
void main(){
double a = 1.0, b = 1.0;
std::vector<GeneralFunc> my_functions;
//fill my_functions from input
for (auto& f : my_functions)
{
double v = f(a, b);
}
}
I think there's an option you didn't include (which is the one I'd use for performance critical code), that is to create a tuple of function objects and "iterate" over such tuple. Unfortunately there is no nice API to iterate over a tuple, so one has to implement his own. See the snippet below
#include <tuple>
#include <functional>
template<int ... Id, typename Functions>
auto apply(std::integer_sequence<int, Id ...>, Functions& my_functions, double& v, double a, double b){
([](auto a, auto b){a=b;}(v, std::get<Id>(my_functions)( a, b )), ...);
}
int main(){
auto fA = [](double a, double b){return a*b;};
auto fB = [](double a, double b){return a+b;};
//create the tuple
auto my_functions=std::make_tuple(fA, fB);
double v=0;
double a = 1.;
double b = 1.;
//iterate over the tuple
apply(std::make_integer_sequence<int, 2>(), my_functions, v, a, b);
}
This way you create a type safe zero overhead abstraction, since the compiler knows everything about the types you use (you don't need any type erasure mechanism). Also there's no need of virtual functions (same as in CRTP), so the compiler will probably inline the function calls. The snippet above uses C++17 generic lambdas, could be also implemented in C++14 or C++11 compliant way, but it would be more verbose. I would prefer this over CRTP because to me it looks more readable: no static cast to the derived class, and no artificial hierarchy of inheritance.
EDIT: from your answer looks like you don't really need the CRTP here, what you write using the CRTP solution is equivalent to this
enum ftype { A = 0, B, C };
auto fA = [](double a, double b){return a*b;};
auto fB = [](double a, double b){return a+b;};
int main(){
std::vector<ftype> types(2);
types[0]=A;
types[1]=B;
auto value = [&types](double a, double b, ftype i){
switch(i){
case (ftype::A):
return fA(a,b);
break;
case (ftype::B):
return fB(a,b);
break;
}
};
double v=value(1., 1., A);
v=value(1., 1., B);
}
Might be a matter of taste, but I think the version above is more readable (you don't really need a common base class, or static cast to the derived class).
So, I have found this code in a book:
class complex
{
public:
float x,y;
complex(float a, float b) // CONSTRUCTOR
{
x=a; y=b;
}
complex sum (complex z)
{
***complex c;*** // i get the error here
c.x=x+z.x;
c.y=y+z.y;
return c;
}
};
This code is supposed to help me sum 2 complex numbers, like this:
int main ()
{
complex a(1,2),b(1,1),c; // first number in paranthesis is the real part, the
// second one is the imaginary part
c=a.sum(b) ; // c should get the value of a+b (c.x=2, c.y=3)
return 0;
}
But everytime I try to compile it I get this error:
"no matching function for call to complex::complex()"
Why? What should I do ?
You defined your own constructor, therefore the default constructor is defined as complex() = delete;. You either need your own constructor or force the default one to be created
class complex
{
public:
float x = 0;
float y = 0;
complex() = default; // Compiler will generate the default constructor
complex(float a, float b): x(a), y(b) {}
complex sum (complex z)
{
complex c;
c.x=x+z.x;
c.y=y+z.y;
return c;
}
};
Instead of creating sum member function, I would create non-member operator+
// No need to make it friend because you declared x and y as public
complex operator+(complex const& a, complex const& b) {
return complex(a.x + b.x, a.y + b.y);
}
and use it like this
complex a(3, 4), b(5, 6);
complex c = a + b;
I want to implement the Euler method in two dimensions and I don´t want to use any library (for practice).
Therefore I want to use my own linear algebra with overloaded functions.
The two first overloads seem to work but there´s still a problem with the multiplication matrix * vector i.e a (2x2)*(2x1).
class vector{
public:
double a;
double b;
vector::vector();
vector::vector(double a, double b){
this->a = a;
this->b = b;
};
vector operator+(vector &a);
vector operator*(double factor);
vector operator*(matrix &B);
};
class matrix{
public:
double a1;
double a2;
double b1;
double b2;
matrix::matrix();
matrix::matrix(double a1, double a2, double b1, double b2) {
this->a1 = a1;
this->a2 = a2;
this->b1 = b1;
this->b2 = b2;
};
};
vector vector::operator+(vector& v){
return vector(this->a+v.a,this->b+v.b);
};
vector vector::operator*(double factor){
return vector(this->a*factor, this->b*factor);
};
vector vector::operator*(matrix& B){
vector newv(this->a*B.a1 + B.a2*b, this->a*B.a1 + B.b2*b);
return newv;
};
Errors when I compile it:
'vector vector::operator *(matrix &)' : overloaded member function not found in 'vector'
unable to resolve function overload
Since you're a bit short on details, I must fill in the gap with guesses. My guess is that you try to support something like the following:
matrix m;
vector v, w;
// fill m and v with values
w = m*v;
I'm also guessing that your matrix has the following form:
( a1 a2 )
( b1 b2 )
You now have two options: Either implement matrix-vector multiplication in the class matrix, or implement it as a free function.
If you want to put if in the matrix class, you'd change the code as follows (note that there are many more things for the code that should be changed, but those are unrelated to the question):
class vector
{
// omit the operator* for matrix, otherwise unchanged
};
class matrix
{
// all that's already in the class
vector operator*(vector const& v) const;
};
vector matrix::operator*(vector const& v) const
{
return vector(a1*v.a + a2*v.b, b1*v.a + b2*v.b);
}
// the rest of your code
If you want to make it a free function (I personally would do it that way, but I'm sure that opinion is not universally held), you'd write
class vector
{
// omit the operator* for matrix, otherwise unchanged
};
class matrix
{
// completely unchanged
};
vector operator*(matrix const& m, vector const& v)
{
return vector(m.a1*v.a + m.a2*v.b, m.b1*v.a + m.b2*v.b);
}
// the rest of your code
I would prefer a BLAS library as an implementation in long term against reinvent the wheel again for basic matrix operations. Additionally some of the BLAS libraries are multithreaded and/or GPU based; they are widely used and tested.
In terms of design I would introduce functions what could be easily implemented by BLAS against operators:
C = α * A + β * B
C = α * A * B + β *C
So as a header:
...
bool blasAdd(const double alfa_, const Matrix& A_, const double beta_, const Matrix& B_, Matrix& C_);
bool blasMultiply(const double alfa_, const Matrix& A_, const Matrix& B_, const double beta_, Matrix& C_);
...
In this way your code automatically could be optimized for BLAS.
My favorite BLAS implementation is Intel MKL, but there are also many free BLAS implementations in the market (e.g.: boost BLAS).