【问题标题】:How to implement function with one argument that swaps private content of objects如何使用一个交换对象私有内容的参数来实现函数
【发布时间】:2019-10-09 15:28:30
【问题描述】:

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

【问题讨论】:

  • 你说的是成员函数吗?喜欢MyClass::swapTrees(MyClass& other)
  • 是的。我想我需要一些帮助功能。
  • 你可以使用std::swap

标签: c++ function class binary-tree binary-search-tree


【解决方案1】:

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

【讨论】:

  • 这看起来像我正在寻找的东西。我会在今天晚些时候回到编程并回复你,谢谢。
  • 顺便说一句,我以前从未见过明确的和 noexcept 使用过。他们有必要吗?我不知道我的考官是否允许我使用它们。
  • @David 然后排除它们。:)
  • 只是想让您知道它效果很好,非常感谢。
【解决方案2】:

你可以创建一个成员函数并在你的树上调用std::swap

class MyClass
{
public:
    void swapTrees(MyClass& other)
    {
        std::swap(tree, other.tree);
    }

private:
    Tree tree;    
};

用法是

MyCalss a, b;
a.swapTrees(b);

【讨论】:

    猜你喜欢
    • 2019-04-26
    • 2018-03-18
    • 2023-03-31
    • 2022-07-21
    • 2018-03-13
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多