【问题标题】:No viable overloaded '=' error even when I overloaded the assignment即使我重载了分配,也没有可行的重载'='错误
【发布时间】:2018-08-12 18:37:21
【问题描述】:

几乎已经提出了确切的问题,但我认为我的问题不太相似。我将在下面的代码中解释:

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 类中的赋值编写了重载函数,并且我设法在早些时候正确地重载了​​&lt;&lt;。我是 C++ 新手,重载是一个非常新的概念,但我不知道为什么会抛出这个错误。

如何解决?

【问题讨论】:

  • 您在调用赋值时将指针传递给 person,而重载却排除 Person const &。
  • A[top] = P; 必须是 A[top] = *P;
  • 顺便说一句,规范接口是Person&amp; operator = (const Person &amp;P);
  • 您的operator = 返回void。这就是它抛出该错误的原因。将其更改为 Person operator=(const Person &amp;p) 并从函数中添加 return *this;
  • @Fall0ut,也就是说,你可能没有void operator = (const Person &amp;P)Person&amp; operator = (const Person &amp;P)

标签: c++ error-handling operator-overloading overloading assignment-operator


【解决方案1】:

您只定义了operator =,它采用(引用)Person,但您试图分配一个指针Person*。未定义执行此类操作的运算符,因此出现错误。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 2018-03-01
    • 2017-11-10
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    相关资源
    最近更新 更多