我创建了一个存储私有表达式树的类。我必须向此类添加一个函数,该函数将其自己的类型作为参数并交换这些对象的树。如果我可以使用 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句