简体   繁体   中英

Free functions in C++

I want to add v2 to v1. My member function is working, but free function is not. How can I solve this problem, thanks.

When I compile with: clang++ -std=c++2a hw1.cpp -o hw1 and run with: ./hw1

give 5 as output.

#include <iostream>

using namespace std;

struct Vector3D
{
    int x;
    int y;
    int z;

    Vector3D(int x_, int y_, int z_)
    {
        x = x_;
        y = y_;
        z = z_;
    }

    void add(Vector3D v)
    {
        x = x + v.x;
        y = y + v.y;
        z = z + v.z;
    }

    ~Vector3D()
    {     
    }
};

void add_free(Vector3D v1, Vector3D v2)
{
    v1.x = v1.x + v2.x;
    v1.y = v1.y + v2.y;
    v1.z = v1.z + v2.z;
}

int main(int argc, char const *argv[])
{
    Vector3D v1(1, 2, 3);
    Vector3D v2(4, 5, 6);
    Vector3D v3(7, 8, 9);
    
    add_free(v1, v2);
    v1.add(v2);
    cout << v1.x << endl;
    
    return 0;
}

You need to pass the Vector3D you'll modify by non-const reference:

void add_free(Vector3D &v1, Vector3D v2)
//                     ^ HERE

Also you can use v1.x += v2.x instead of v1.x = v1.x + v2.x; .

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