c++ - 如何重载运算符=

标签 c++ operator-overloading

我正在尝试将赋值运算符重载为成员函数,以将字符串作为参数并将其值赋给当前对象 A。我在下面的评论中发布了错误。

有人可以告诉我我做错了什么吗?我认为它与参数有关,可能与定义中的代码有关。

我不确定我是否声明正确,但我是这样声明的:

WORD operator=(const string& other);

我是这样定义的:

WORD WORD::operator=(const string& other) //<---not sure if I did the parameters Correctly
{
(*this) = other;
return (*this);
}

如果有帮助,这里是完整的文件:

#include <iostream>

using namespace std;

#pragma once

class alpha_numeric //node
{
   public:
char symbol; //data in node
alpha_numeric *next;//points to next node
};

class WORD
{
   public:
      WORD() : front(0) {length=0;}; //front of list initially set to Null
      WORD(const WORD& other);
      bool IsEmpty();
      int Length();
      void Insert(WORD bword, int position);
      WORD operator=(const string& other); 

   private:
      alpha_numeric *front; //points to the front node of a list
      int length;
};

WORD WORD::operator=(const string& other) //<---not sure if I did the parameters Correctly
{
      (*this) = other;
      return (*this);
}

最佳答案

好的 2 件事:

首先,您缺少复制构造函数的定义,因此无法编译。 在你的类里面试试这个(只显示部分实现):

WORD(const WORD& other)
: length(other.length)
{
    // Construct me !
}

其次,您的赋值运算符是正确的,但在所有控制路径上都是递归的。例如。它无限期地称呼自己。您可能希望在方法内部分配成员(同样,仅显示部分实现):

WORD WORD::operator=(const string& other)
{
    // Only copy the length, the rest is to be filled
    this.length = other.length;
    return (*this);
}

最后,正如其他人所指出的,您的可执行文件中有相同符号的多个定义。要解决这个问题,您必须确保您的 header 只包含一次(#pragma once 应该会处理这个问题),而且还要将所有实现细节从 header 文件移到源文件中。例如将 WORD WORD::operator=(const string& other) 的定义移动到 CPP 文件中。

关于c++ - 如何重载运算符=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10842883/

相关文章:

c++ - 模板化重载运算符解析,无隐式转换

c++ - 隐式类型转换不适用于模板类

C++11 - 区分右值指针

c++ - 作业 - 运算符重载货币类 - 卡住/丢失

C++ 简单指针错误无法弄清楚为什么?

perl - 您如何检查对象是否重载了 XS 中的运算符?

swift - 子类化 Swift double /运算符重载类型别名

c++ - 如何使用 Visual Studio 编译 libtasn1?

c++ - 返回 0 隐式

c++ - boost.log std::exception格式化程序无法在自己的命名空间中找到运算符<<重载