如何使用Struct打印交换功能

时间:2019-11-16 18:06:40

标签: c++ function pointers

您能帮我怎样打印我的swap3函数?我将非常感谢。 我是编程的初学者

#include <iostream>
using namespace std;

struct Pair{
    int x;
    int y;
};

Pair* swap3(const Pair& p){
    Pair *t = new Pair();
    t->x = p.y;
    t->y = p.x; 
    return t;
}

int main(){

    int f = Pair(2,3);
    swap3(f);
    cout<<f<<endl;
    return 0;


}

我的主要功能是否为假?

1 个答案:

答案 0 :(得分:3)

您需要重载ostream运算符:

 friend std::ostream &operator<<(std::ostream &os, const Pair& pair) {
    os << pair.x << " " << pair.y << '\n';
    return os;
 }

如果您对操作员的全部操作不满意,则可以简单地单独打印元素:

cout<< f.x <<" "<< f.y <<'\n';

构造f的方式也是错误的(intPair不是同一类型)。您可以改用list initialization

Pair f{2,3};
auto s = swap3(f);
cout<<f<<endl;
delete s;

请注意,您的代码中存在内存泄漏,因为您的函数返回了一个指针,所以您不存储它并且永远不会删除它。

我建议使用智能指针来避免内存泄漏:

std::unique_ptr<Pair> swap3(const Pair& p){
    auto t = make_unique<Pair>(Pair{});
    t->x = p.y;
    t->y = p.x; 
    return t;
}

Godbolt上直播

P.S。 我不确定要从交换中获得什么,在您发布的代码中,根本不需要指针。我认为交换应该这样写:

void swap3(Pair& p1, Pair& p2){
    Pair tmp{p1.x, p1.y};
    p1.x = p2.x;
    p1.y = p2.y;
    p2.x = tmp.x;
    p2.y = tmp.y;
}

或:

void swap3(Pair& p){
    Pair tmp{p.x, p.y};
    p.x = tmp.y;
    p.y = tmp.x;
}

Godbolt上直播