即使我重载了分配,也没有可行的重载'='错误

No viable overloaded '=' error even when I overloaded the assignment

本文关键字:重载 错误 分配      更新时间:2023-10-16
几乎

已经问了确切的问题,但我认为我的问题不是很相似。我将在下面解释代码:

class Person{
public:
    string name;
    int age, height, weight;
    Person(string name = "empty", int age = 0, int height = 0, int weight = 0) {
        this->name = name;
        this->age = age;
        this->height = height;
        this->weight = weight;
    }
    void operator = (const Person &P){
        name = P.name;
        age = P.age;
        height = P.height;
        weight = P.weight;
    }
    friend ostream& operator<<(ostream& os, const Person& p);
};
class Stack{
public:
    int top;
    Person* A;
    int size;
    Stack(int s){
        top = -1;
        size = s;
        A = new Person[size];
    }
    bool isEmpty(){
        if(top == -1)
            return true;
        else
            return false;
    }
    bool isFull(){
        if(top >= size-1)
            return true;
        else
            return false;
    }
    void Push(Person* P){
        if(isFull()){
            cout << "No Space on Stack" << endl;
            return;
        }
        top++;
        A[top] = P;
    }
};

在代码底部A[top] = P;行上,我收到错误No viable overloaded '='.

我不明白为什么这不起作用。我在 Person 类中为赋值编写了重载函数,并且我设法更早地重载<<。我是C++新手,重载是一个非常新的概念,但我无法弄清楚为什么会抛出此错误。

如何解决?

您只定义了operator = Person,但您尝试将指针Person* 。未定义执行此类操作的运算符,因此您遇到了错误。

要修复,有一些选项取决于预期的使用情况。

  • 在分配之前取消引用指针
  • Push的参数更改为复制或引用Person,而不是指针
  • 添加需要Person * class Person operator =