首页 > 试题广场 >

移动构造函数

[编程题]移动构造函数
  • 热度指数:50 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
为类A实现默认构造函数,以std::string为参数的构造函数,移动构造函数(move constructor),重载移动赋值操作符(operator=),析构函数,同时禁止该类进行复制构造(copy constructor),使得以下代码能够运行通过:


#include <iostream>
#include <string>

class A {
public:
    std::string s() const {
        return *_s;
    }
private:
    std::string *_s;
};

int main() {
    std::string input;
    std::cin >> input;
    A a(input);
    A b(std::move(a));
    std::cout << b.s() << std::endl;
    A c;
    c = std::move(b);
    std::cout << c.s() << std::endl;
    return 0;
}

输入描述:
一行字符串


输出描述:
两行字符串
示例1

输入

abcd

输出

abcd
abcd
#include <iostream>
#include <string>

class A {
public:
    //构造函数
    A(const std::string& str)
    {
        _s = new std::string(str);
    }
    A(){}
    //重载赋值运算
    void operator=(const std::string& str)
    {
        if (_s) delete _s;
        _s = new std::string(str);
    }
    //移动构造函数
    A(std::string&& str)
    {
        if (_s) delete _s;
        _s = &str;
        //delete& str;
    }
    std::string s() const {
        return *_s;
    }
private:
    std::string* _s;
};

int main() {
    std::string input;
    std::cin >> input;
    A a(input);
    A b(std::move(a));
    std::cout << b.s() << std::endl;
    A c;
    c = std::move(b);
    std::cout << c.s() << std::endl;
    return 0;
}

发表于 2022-03-16 16:37:29 回复(0)