c++ - 如何使用一个交换对象私有内容的参数来实现函数
问题描述
我创建了一个存储私有表达式树的类。我必须向此类添加一个函数,该函数将其自己的类型作为参数并交换这些对象的树。如果我可以使用 2 个参数,我想我可以创建一个朋友函数。对于如何实现这样的功能,我将不胜感激。
解决方案
这是一个演示程序,展示了如何定义成员函数 swap。
#include <iostream>
#include <utility>
class A
{
private:
int x;
public:
explicit A( int x = 0 ) : x( x ) {}
void swap( A &a ) noexcept
{
int tmp = std::move( a.x );
a.x = std::move( this->x );
this->x = std::move( tmp );
}
void swap( A &&a ) noexcept
{
int tmp = std::move( a.x );
a.x = std::move( this->x );
this->x = std::move( tmp );
}
const int & getX() const { return x; }
};
int main()
{
A a1( 10 );
A a2( 20 );
std::cout << "a1.x = " << a1.getX() << '\n';
std::cout << "a2.x = " << a2.getX() << '\n';
a1.swap( a2 );
std::cout << "a1.x = " << a1.getX() << '\n';
std::cout << "a2.x = " << a2.getX() << '\n';
a1.swap( A( 30 ) );
std::cout << "a1.x = " << a1.getX() << '\n';
return 0;
}
程序输出为
a1.x = 10
a2.x = 20
a1.x = 20
a2.x = 10
a1.x = 30
推荐阅读
- react-redux - 如何使用 react hooks、redux 将图像上传到数据库?
- postgresql - 如何在 Postgresql 中存储列表?
- laravel - 如何为 Laravel 中的每种异常设置不同的日志级别?
- delphi - 使用 GDI+ 的线程 JPEG 解码随机触发“没有足够的内存资源可用于处理此命令”
- excel - 从三个工作表上的三个列表中提取唯一值
- wordpress - 拒绝在框架中显示“https://www.google.com/”,因为它在 Wordpress 中将“X-Frame-Options”设置为“sameorigin”
- swift - 从另一个类访问变量给 0 swift
- angular - 无法通过在 angular-slickgrid 中向左或向右拖动来操纵列大小
- kubernetes - 谁将 ClusterIP 分配给 kubernetes 中的服务,可以禁用它吗?
- vue.js - 全局混合与本地导入的混合 - 对所有混合使用全局混合有什么缺点吗?