gpt4 book ai didi

c++ - 使用类的对象作为方法中的参数

转载 作者:行者123 更新时间:2023-11-28 05:47:24 25 4
gpt4 key购买 nike

我有 Stack 类的方法,它比较这个类的 2 个对象:

bool comparison(T &stack) {
if (size == stack.size)
for (int i = 0; i < size; i++) {
if (!this->stackPr[i].comparison(stack.stackPr[i]))
return false;
}
else
return false;
return true;
}

并使用Time类的方法:

bool comparison(Time &time) {
if ((this->hours == time.hours) && (this->minutes == time.minutes) && (this->seconds == time.seconds))
return true;
return false;

当我尝试在 main 中使用此命令时:

bool temp = stack3.comparison(stack4);

MVS 下划线 |stack4|并向我显示错误:

a reference of type "Time &"(non-const qualified) cannot be initialized with a value of type Stack<Time>

我该如何处理这个问题?感谢您的回答:)

有类Stack:

class Stack {
private:
T *stackPr;
int size;
int top;
public:
//----------------CONSTRUCTORS-----------------
Stack(int n) {
if (n > 0)
size = n;
else
size = 10;
stackPr = new T[size];
top = -1;
}
Stack() {
size = 10;
stackPr = new T[size];
top = -1;
}
Stack(Stack &stack) {
stackPr = new T[stack.size];
size = stack.size;
top = stack.top;
for (int i = 0; i < size; i++)
stackPr[i] = stack.stackPr[i];
}
Stack(T *objs, int sizeMass) {
size = sizeMass;
stackPr = new T[size];
for (int i = 0; i < sizeMass; i++) {
this->push(objs[i]);
}
}

//----------------DESTRUCTOR-------------------
~Stack() {
delete[] stackPr;
}

//-----------------METHODS---------------------

//Add element to stack
void push(T &element) {
if (top == size - 1)
cout << "\nThere's no more place!!!\n";
else {
top++;
stackPr[top] = element;
cout << "\nElement was succesfully pushed\n";
}
}

//Read + Delete
T pop() {
if (top == -1)
cout << "\nStack is empty\n";
else {
T temp = stackPr[top];
stackPr[top] = 0;
top--;
cout << "\nElement was succesfully poped and deleted\n";
return temp;
}
}

//Read
T popup() {
if (top == -1)
cout << "\nStack is empty\n";
else {
cout << "\nElement was succesfully popped\n";
return stackPr[top];
}
}

//Comparison of 2 stacks
bool comparison(T &stack) {
if (size == stack.size)
for (int i = 0; i < size; i++) {
if (!this->stackPr[i].comparison(stack.stackPr[i]))
return false;
}
else
return false;
return true;
}
};

最佳答案

在你的 Stack 类中试试这个

改变:

bool comparison(T &stack) {

为此:

bool comparison(Stack<T> &stack) {

关于c++ - 使用类的对象作为方法中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35959635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com