c++ - 为类重载 "*"运算符以返回类变量

标签 c++ move-semantics move-constructor constructor-overloading move-assignment-operator

我有两个cpp文件和一个hpp文件。 Main.cpp、Ab.cpp 和 Ab.hpp。

在这些文件中,我创建了一个类“Ab”,它有一个默认的构造函数, 一个接受字符串的构造函数。在类中,我想重新定义 * 运算符以将给定值设置为类的对象,并删除分配给它的任何先前值。

值得一提的是,我被指示不允许在此任务中使用任何复制构造函数或复制赋值。这意味着我必须求助于使用纯粹的 move 构造函数和 move 赋值。在这些主题中,我的知识非常有限,因为我之前只使用过基本的 C#。

Main.cpp 如下:

#include <iostream>
#include "Ab.hpp"

A MoveTest(std::string testData)
{
    return Ab(new std::string(testData));
}

int main()
{
    std::cout << "-----'Ab' Test Begin-----" << std::endl;


    std::cout << "'Ab' test: Constructor begins." << std::endl;
    Ab emptyAb;
    Ab moveTestAb(new std::string("To remove"));
    std::cout << "'Ab' test: Constructor done. Press enter to continue." << std::endl;
    std::cin.get();

    std::cout << "Ab' test: Moveoperator begins." << std::endl;
    moveTestAb = MoveTest("This is a test movement");
    std::cout << "Expected output:         " << "This is a test movement" << std::endl;
    std::cout << "Output from moveTestAb: " << *moveTestAb << std::endl;
    std::cout << "'Ab' test: Moveoperator done. Press enter to continue." << std::endl;
    std::cin.get();
    std::cout << "-----'Ab' Test End-----" << std::endl;
    std::cin.get();
}

Ab.cpp如下:

#include "Ab.hpp"

std::string Ab::Get() const
{
    return "test";
}
bool Ab::Check() const
{
    bool return_value = true;
    if (this==NULL)
    {
        return_value = false;
    }
    return return_value;
}

Ab & Ab::operator=(const Ab &ptr)
{
    return *this;
}


Ab & Ab::operator*(Ab &other)
{
    if (this != &other) {
        delete this->a_string;
        this->a_string = other.a_string;
        other.a_string = nullptr;
    }
    Ab *thing_to_return = &Ab(this->a_string);
    return *thing_to_return;  
}

Ab.hpp如下

#include <string>
class Ab
{
    Ab(const Ab&) = delete;

    std::string* a_string;
    public:
        Ab &operator=(const Ab&);

    Ab& operator*(Ab&);



        Ab();
        Ab(std::string *the_string):
        a_string(the_string){};
        int b = 0;
        int a = 3;
        std::string Get() const;
        ~Ab() = default;
        bool Check() const;

    private:
        int z = 0;
};

我目前遇到错误:

no operator "*" matches these operands -- operand types are: * AB

最佳答案

Ab& operator*(Ab&);

这不允许您执行*ab。当您执行 ab*ab 时会调用此运算符; https://gcc.godbolt.org/z/SDkcgl

Ab *thing_to_return = &Ab(this->a_string);

在这里你将指针指向一个临时的。您的代码存在更多问题。我建议逐步重写

关于c++ - 为类重载 "*"运算符以返回类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53732063/

相关文章:

c++ - 我们如何使用 boost::mpl 实现 Builder 设计模式?

c++ - operator= 和 C++ 中未继承的函数?

c++ - 什么是 C++ 中的复制/移动构造函数选择规则?移动到复制回退何时发生?

c++ - C++ 编译器是否允许仅使用构造来替换构造+移动构造?

c++ - 具有成员 std::vector 的移动语义

c++ - 没有重载函数的实例匹配参数列表 C++

C++ 对象构造函数通过 const 引用复制传递

c++ - 我应该将临时变量 move 到变量中吗?

C++11 将一个 vector move 到另一个 vector - 将右值引用传递给构造函数

c++ - 无法将 std::function move 到 map 中