【发布时间】:2017-05-05 00:10:57
【问题描述】:
我不明白为什么第 21 行正常但第 25 行出错?
错误消息:
从 'const int*' 到 'int*' 的无效转换 [-fpermissive]
Push 是类中的函数,如下所示:
template< typename Type >
class Stack {
void Push(const Type& value) {
SNode* type = new SNode();
if (this->head != nullptr) {
this->head->up = temp;
}
temp->value = value;
temp->up = nullptr;
temp->down = head;
temp->head = temp;
num_of_elements++;
}
};
int main() {
Stack<int*>* stk = new Stack<int*>();
int a = 5;
int* x = &a;
stk->Push(x); //this line is fine
const int b = 5;
const int* y = &b;
stk->Push(y); //this line is an error
delete stk;
return 0;
}
它看起来像函数 Push get parameter from type of "const int * &" ,在第 25 行,我准确地发送了一个 const 指针 "const int *"。那么问题出在哪里?
【问题讨论】:
-
如果您有一个更好的标题并且在您的问题中包含错误消息会有所帮助。您可能还希望将相关函数设为非私有。
-
您的错误是认为
Push()正在等待const int * &;它正在等待int * const &;完全不同的类型(希望我的回答能更好地解释)。
标签: c++ class c++11 templates constants