【问题标题】:Hello, can someone help me with this error?你好,有人可以帮我解决这个错误吗?
【发布时间】: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 * &amp;" ,在第 25 行,我准确地发送了一个 const 指针 "const int *"。那么问题出在哪里?

【问题讨论】:

  • 如果您有一个更好的标题并且在您的问题中包含错误消息会有所帮助。您可能还希望将相关函数设为非私有。
  • 您的错误是认为Push() 正在等待const int * &amp;;它正在等待int * const &amp;;完全不同的类型(希望我的回答能更好地解释)。

标签: c++ class c++11 templates constants


【解决方案1】:

第 21 行中的 Push()

int a = 5;
int * x = &a;
stk->Push(x);

其中Push() 等待const Type &amp; value(如果我理解正确,Type 等于int *),因为您将int * 发送到等待兼容类型的方法,const Type &amp;int * const &amp;

请记住,const 应用于左侧,当左侧没有任何内容时应用于右侧,因此 const Type &amp;Type const &amp;int * const &amp;。对指向非恒定整数的常量指针的引用也是如此。

当你写的时候(Push() 在第 25 行)

const int b = 5;
const int * y = &b;
stk->Push(y);

您正在发送一个const int *,即int const *(指向一个常量整数的非常量指针),该方法正在等待int * const &amp;(一个指向一个非常量指针的引用) -常数整数)。

这两种类型不兼容,所以报错。

你可以试试

int b = 5;
int * const y = &b;
stk->Push(y);

这应该可行。

【讨论】:

  • 那么如果Type是指针,那么我怎么写,那么被指针的地方就是const?
  • @BestMath 改成Stack&lt;const int*&gt; 而不是Stack&lt;int*&gt;
猜你喜欢
  • 2016-07-09
  • 1970-01-01
  • 2019-09-23
  • 1970-01-01
  • 2022-10-23
  • 1970-01-01
  • 2021-07-10
  • 2016-07-25
相关资源
最近更新 更多