c++ - 如何使用 Struct 打印交换函数
问题描述
你能帮我吗,我怎样才能打印我的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;
}
我的主要功能是假的吗?
解决方案
你需要重载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
也是错误的(int
并且Pair
不是同一类型)。您可以尝试列表初始化:
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;
}
住在神螺栓上
PS我不确定你想从交换中得到什么,在你发布的代码中,你根本不需要指针。我认为交换应该写成:
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;
}
住在神螺栓上
推荐阅读
- android - 杀死应用程序通知点击意图 putExtra 方法不起作用
- elasticsearch - Elascticsearch 索引中新添加的关键字字段不可搜索
- mysql - 将字符串转换为日期格式并检索周数
- javascript - NodeJS:如何在 JSON.parse() 的返回值中添加一个变量?
- jvm - JVM 堆/堆栈与虚拟地址空间堆/堆栈不同吗?
- javascript - JavaScript对象将值设置为对象但不更新到firebase
- node.js - pg-node 中的日期格式
- ember.js - 使用 ember font-awesome 时如何操作图层文本?
- swift - SwiftUI macOS 在 TextField 处于活动状态时使用箭头键滚动列表
- javascript - 我如何在 JSON 的属性中获取属性?