2016-05-15 222 views
-2

我该如何解决它?在主函数中,当我试图让新节点有字符串数据时,它不能。错误消息是[错误]无法在分配中将'const std :: basic_string'转换为'int'。我该怎么做??C++错误:无法将const std :: basic_string <char>'转换为int中的int

template <typename value_type> 
class node : public element 
    public : 
    value_type data; 
    node(); 
    node (const value_type& T); 
    ~node(); 
}; 
template <typename value_type> 
node<value_type> :: node(const value_type& T) 
{ 
    type = 0; 
    intd= 0; 
    stringd = ""; 
    if(typeid(T)==typeid(int)) 
    { 
     type= 0;intd = T; 
    } 
    else if(typeid(T)==typeid(string)) 
    { 
     type = 3;stringd = T; 
    } 
    this->left = NULL; 
    this->right = NULL; 
    this->data = T; 
} 
int main() 
{ 
    string s1 = "123"; 
    node *n1 = new node<string>(s1); 
    return 0; 
} 
+1

不要使用'typeid'为,请...'type = 0; intd = T;'仍然需要编译,即使条件是'false'。 – LogicStuff

回答

0

的问题是这一行:

if(typeid(T)==typeid(int)) 
{ 
    type= 0;intd = T; // *** here *** 
} 

虽然你动态检查typeid(T)==typeid(int)分配Tint变量之前,C++是静态类型。分配不会编译,因为您无法将string分配给int变量。

相反,你可以使用模板特:

#include <string> 
#include <typeinfo> 
using std::string; 
struct element{ 
    int type, intd; 
    string stringd; 
    void *left, *right; 
}; 

template <typename value_type> 
class node : public element{ 
    public : 
    value_type data; 
    node(); 
    node (const value_type& T); 
    ~node(); 
}; 

template <typename value_type> 
node<value_type> :: node(const value_type& T) 
{ 
    type = 0; 
    intd= 0; 
    stringd = ""; 
    this->left = NULL; 
    this->right = NULL; 
    this->data = T; 
} 

template <> 
node<int> :: node(const int& T) 
{ 
    type= 0; 
    intd = T; 
    stringd = ""; 
    this->left = NULL; 
    this->right = NULL; 
    this->data = T; 
} 

template <> 
node<string> :: node(const string& T) 
{ 
    type = 3; 
    intd= 0; 
    stringd = T; 
    this->left = NULL; 
    this->right = NULL; 
    this->data = T; 
} 

// defining destructor is required to use delete 
template <typename value_type> 
node<value_type> :: ~node() 
{ 
} 

int main() 
{ 
    string s1 = "123"; 
    node<string> *n1 = new node<string>(s1); 
    delete n1; 
    return 0; 
} 

我也

  • class node : public element后添加{
  • 更改n1nodenode<string>的类型以避免编译错误。
0

你最终想要把你的节点对象放入某种容器中,如链接列表。容器不处理不同类型的元素。你可以在容器中存储void *指针来隐藏它们的内部细节。但是,你放弃了编译器类型检查。

获得类型检查的一种方法是隐藏在boost :: variant类中保存多个类型的机制。你Node对象则不需要进行模板化,因为你声明data为:

boost::variant<int, string> data; 

boost::variant<int, string>将处理intstring只,但您可以添加更多的模板参数来处理更多类型,例如boost::variant<int, string, double>

如果你有兴趣在如何处理这个棘手的问题引擎盖下看,检查出由沃尔克·西蒙尼斯和罗兰·魏斯这个伟大的开创性文章:http://www.progdoc.de/papers/nseq/nseq/nseq.html

相关问题