简体   繁体   中英

call function without object in c++

I am new to c++ and have a trouble with functions that does not seems to be a bit unusual (or maybe I just do not know the right name). I have created a class vector that is supposed to work like the c++ vector, but is probably a bit simpler. I know that whenever possible you should use the already existent classes, but for the practice I want to create an own vector class.

So what I want to do is simply to create a function that can be called somehow "stand alone". Earlier I have managed to create a function scalar (calculates scalar product) that can be called like,

myVector v1(5);
myVector v2(5);

for(int i=0; i<5; i++){ //missing proper function here, this is not part of the question
    v1[i] = i;
    v2[i] = i+1;
}
double prod = v1.scalar(v1,v2);
//or better
double prod2 = v1.scalar(v2);

However what I really want to do is to create a function that does not need to operate on an object to work. I want to use the function something like

double prod3 = scalar(v1,v2);

is this possible and where should I define the function. I do want it to have the properties of an ordinary function rather than a inline function if possible. Also if this kind of functions have a name I would be happy to know.

/BR Patrik

You could declare the function outside the vector class but in the same namespace/file and then define it accordingly.

For example:

namespace math {
    class Vector
    {
       ...
    }

    double scalar(const Vector& v1, const Vector& v2);
}

And then in the cpp:

namespace math {
    Vector::Vector()
    {
       ...
    }

    double scalar(const Vector& v1, const Vector& v2)
    {
        ...
    }
}

You don't need to use namespace but it makes it cleaner in my opinion. Call would look like:

math::Vector v1;
math::Vector v2;

double prod = math::scalar(v1, v2);


As pointed out in the comments, you could also put the method as a static member of the class. It is also a way to avoid adding to the global namespace. You can do it like so:

class Vector
{
    static double scalar(const Vector& v1, const Vector& v2);
}

And then call it:

myVector v1;
myVector v2;

...

double prod = myVector::scalar(v1,v2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM