首页 > 解决方案 > 如何使用一个交换对象私有内容的参数来实现函数

问题描述

我创建了一个存储私有表达式树的类。我必须向此类添加一个函数,该函数将其自己的类型作为参数并交换这些对象的树。如果我可以使用 2 个参数,我想我可以创建一个朋友函数。对于如何实现这样的功能,我将不胜感激。

标签: c++functionclassbinary-treebinary-search-tree

解决方案


这是一个演示程序,展示了如何定义成员函数 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

推荐阅读