程式大概是這樣:
template<typename T>
class Avl {
std::list<T*> pdata;
int add(const T *item) {
pdata.push_back(item);
}
};
main() {
node_t a;
Avl<node_t> avl;
avl.add(&a)
}
然后編譯報錯如下:
In file included from ../Welcome_1/welcome.cc:33:0:
../Welcome_1/Avl.h: In instantiation of ‘int Avl<T>::add(const T*) [with T = node_t]’:
../Welcome_1/welcome.cc:129:15: required from here
../Welcome_1/Avl.h:112:5: error: no matching function for call to ‘push_back(const node_t*&)’
pdata.push_back(item);
^
In file included from /usr/include/c++/5.3.1/list:63:0,
from ../Welcome_1/Avl.h:11,
from ../Welcome_1/welcome.cc:33:
/usr/include/c++/5.3.1/bits/stl_list.h:1088:7: note: candidate: void std::list<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = node_t*; _Alloc = std::allocator<node_t*>; std::list<_Tp, _Alloc>::value_type = node_t*] <near match>
push_back(const value_type& __x)
^
/usr/include/c++/5.3.1/bits/stl_list.h:1088:7: note: conversion of argument 1 would be ill-formed:
In file included from ../Welcome_1/welcome.cc:33:0:
../Welcome_1/Avl.h:112:5: error: invalid conversion from ‘const node_t*’ to ‘std::list<node_t*>::value_type {aka node_t*}’ [-fpermissive]
pdata.push_back(item);
不明白為什么函式引數不匹配,明明 push_back(const value_type& __x) 就應該是 push_back(const node_t*&),請大家幫忙看下。
uj5u.com熱心網友回復:
這是泛型的問題list<T>這里的T就包括指標了
所以改成
std::list<T> pdata; //泛型用T就可以了
int add(T item) {
pdata.push_back(item);
return 0;
}
呼叫的時候
node_t a;
Avl<node_t*> avl; //這里指定泛型為指標即可
avl.add(&a);
lz自己對比一下區別吧
uj5u.com熱心網友回復:
樓主:push_back(const value_type& __x) 與push_back(const node_t*&)是不一樣的
value_type被編譯成node_t*,但是,函式引數是(const value_type& __x),此時的const修飾&,等價于(value_type const & __x)
所以,
push_back(const value_type& __x)等價于push_back(node_t* const &)
push_back還有一種多載,右值參考
void push_back(_Ty&& _Val)
&&,就是右值參考了(一個&是左值參考)。
uj5u.com熱心網友回復:
// ConsoleApplication1.cpp : 此檔案包含 "main" 函式。程式執行將在此處開始并結束。
//
#include <iostream>
#include <list>
class node_t {};
template<typename T>
class Avl {
public:
std::list<T*> pdata;
int add(const T* item) {
pdata.push_back(item);
return 0;
}
};
int main()
{
node_t a;
Avl<const node_t> avl;
avl.add(&a);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/227421.html
標籤:C++ 語言
上一篇:新手求教
下一篇:c++STL中仿函式的問題
