调用超载to_string模棱两可



我有两个文件:error.h 和 error.cpp。编译使用

g++ -std=c++0x

给我一个错误:

error.cpp:9:33:**call of overloaded "to_string(char*&)" is ambiguous**

如何解决此问题?

错误.h:

  1 #ifndef ERROR_H_GUARD
  2 #define ERROR_H_GUARD
  4 #include <string>
  6 class Error {
  7   public:
  8     Error(int pos, std::string& msg); 
 10     Error(int pos, char* msg); 
 12     const char* what() throw();
 14   private:
 15     std::string msg;
 17     void setMsg(int pos, std::string& msg);
 18 };
 19 
 20 #endif

错误.cpp:

  2 #include "error.h"
  4 Error::Error(int pos, std::string& msg){
  5   setMsg(pos, msg);
  6 }
  8 Error::Error(int pos, char* msg) {
  9   setMsg(pos, std::to_string(msg));
 10 }   
 12 const char* Error::what() throw() {
 13   return msg.c_str();
 14 } 
 16 void Error::setMsg(int pos, std::string& msg){
 17   this->msg = std::to_string(pos) + msg + std::string("n") + std::string(pos - 1, ' ') + std::string("^");
 18 }

std::to_string 将整数作为参数,但您传递了一个指向它的指针。

Error::Error(int pos, char* msg) {
  setMsg(pos, std::to_string(msg));
} 

您不需要将字符串转换为字符串,请尝试:

Error::Error(int pos, char* msg) {
     setMsg(pos, std::string(msg));
} 

旁注:您的所有函数参数最好都采用常量参考:

Error(int pos, const std::string& msg);
void setMsg(int pos, const std::string& msg);
to_string()用于

不是字符串的东西(例如longint等)转换为string。你有一个char*,它是一个C字符串,你要做的是从中创建一个string对象,而不是转换它。

您的编译器抱怨歧义,因为它找不到您传递给它的类型的to_string()版本(char*),考虑到该函数的目的,这是有道理的。

如果你在相应的 setMsg() 重载(以及 Error 的构造函数中)string const&而不是string&,你可以通过传递 C 字符串直接调用它:将自动创建 string 类型的临时并绑定到 setMsg() 的参数。

这样,您甚至可以摆脱 C 字符串的特定重载 setMsg(),实际上除了转发之外什么都不做。

改用string的构造函数:

std::string(msg)

但请注意,此临时不能绑定到引用参数。你必须解决这个问题。

也许是这样的:

Error::Error(int pos, char* msg) {
   std::string str(msg);
   setMsg(pos, msg);
}

或者使用 const-ref。

删除Error(int pos, char* msg)并将剩余的构造函数和setMsg()更改为

Error(int pos, const std::string& msg);
...
void setMsg(int pos, const std::string& msg);

当你用char*调用Error()时,它将自动使用std::string构造函数。因此,不需要单独的构造函数。

这行不通:

Error::Error(int pos, char* msg) {
   setMsg(pos, std::to_string(msg));
}

因为std::to_string()需要一个数值来转换。你可能的意思是:

Error::Error(int pos, char const * msg) {
   setMsg(pos, msg);
}

这与std::string&版本完全相同(反过来,应该是std::string const &),所以你实际上可以删除这个char*构造函数(更少的代码维护:bonus)!

还有这个:

void Error::setMsg(int pos, std::string& msg){

应该是这样的:

void Error::setMsg(int pos, std::string const & msg){

最新更新