【发布时间】:2011-04-01 19:12:00
【问题描述】:
我有一个 Logger 类,它期望 std::string 以下列方式:
class Logger
{
public:
void Log(const std::string message);
};
另一个班级称它为:
class MyClass
{
public:
void MyMethod()
{
Logger logger;
logger.Log("Hello World!"); // This line is causing linker error.
// std::string myString("Hello World!"); If this and the line below are
// logger.Log(myString); uncommented, I get no errors.
}
};
错误信息是:
Logger.cpp: undefined reference to `Logger::Log(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)`
显然链接器知道 Log 方法,因为正如我上面所展示的,注释掉的行将允许它正确链接。
有人知道发生了什么吗?如果需要更多信息,请告诉我。
这是在Linux下使用gcc 4.4.3(使用Eclipse)
编辑:
我的理解是,你总是可以将 c 风格的字符串传递给一个需要 std::string 的方法,因为 std::string 有一个适当的复制构造函数来处理它。
EDITx2:
捂脸时刻。我发现了错误。感谢大家让我更仔细地查看我的代码。请参阅下面的完整解决方案。
这段代码应该已经添加到问题中了:
// cpp file
// This should have been in the header, not the cpp file.
inline void Logger::Log(const std::string message)
{
/* do sutff */
}
【问题讨论】:
-
您能否验证您的 Log 函数上的签名?大多数人把它写成 const std::string& 或 std::string,而不是 const std::string
-
它是正确的。起初我将它作为 const std::string& ,但将其更改为 const std::string 认为是引用导致了问题。