【发布时间】: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 类中的赋值编写了重载函数,并且我设法在早些时候正确地重载了<<。我是 C++ 新手,重载是一个非常新的概念,但我不知道为什么会抛出这个错误。
如何解决?
【问题讨论】:
-
您在调用赋值时将指针传递给 person,而重载却排除 Person const &。
-
A[top] = P;必须是A[top] = *P; -
顺便说一句,规范接口是
Person& operator = (const Person &P); -
您的
operator =返回void。这就是它抛出该错误的原因。将其更改为Person operator=(const Person &p)并从函数中添加return *this; -
@Fall0ut,也就是说,你可能没有
void operator = (const Person &P)和Person& operator = (const Person &P)。
标签: c++ error-handling operator-overloading overloading assignment-operator