简体   繁体   English

C++ 中的自由函数

[英]Free functions in C++

I want to add v2 to v1.我想将 v2 添加到 v1。 My member function is working, but free function is not.我的会员 function 正在工作,但免费 function 没有。 How can I solve this problem, thanks.我该如何解决这个问题,谢谢。

When I compile with: clang++ -std=c++2a hw1.cpp -o hw1 and run with: ./hw1当我编译时: clang++ -std=c++2a hw1.cpp -o hw1 并运行: ./hw1

give 5 as output.给 5 作为 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:您需要通过非常量引用传递您将修改的Vector3D

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

Also you can use v1.x += v2.x instead of v1.x = v1.x + v2.x;您也可以使用v1.x += v2.x代替v1.x = v1.x + v2.x; . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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