C++ 从std::string到class的隐式转换不';行不通
我在VisualStudio2010中收到一个错误C2664,表示没有从C++ 从std::string到class的隐式转换不';行不通,c++,C++,我在VisualStudio2010中收到一个错误C2664,表示没有从std::string转换到我的类Filename 我真的不明白为什么会发生这种情况,因为我有构造函数来接受std::string,这适用于这样的代码: std::string s = "t"; Filename f1 = s; Filename f2(s); class Filename { public: Filename(std::string const &oFilename, std::strin
std::string
转换到我的类Filename
我真的不明白为什么会发生这种情况,因为我有构造函数来接受std::string
,这适用于这样的代码:
std::string s = "t";
Filename f1 = s;
Filename f2(s);
class Filename
{
public:
Filename(std::string const &oFilename, std::string const &oBasePath = "");
Filename(char const *oFilename = NULL, char const *oBasePath = NULL);
Filename(const Filename &oSource);
virtual ~Filename(void);
void setBasePath(std::string const &oBasePath);
void setBasePath(const char *oBasePath);
const std::string &getBasePath(void) const;
std::string getBaseDir(void) const;
std::string getFileDir(void) const;
};
然而,我有一个功能
FileType FileFactory::detectFileType(Filename &oFilename) const;
在我的代码中,当我尝试
Filename fn = "d:\\tmp\\test.txt";
// getBaseDir() returns an std::string
FactoryFileType type = detectFileType(fn.getBaseDir());
它将获得以下错误:
error C2664: 'FileFactory::detectFileType': conversion of parameter 1 from 'std::string' to 'Filename &' is not possible
我的文件名类如下所示:
std::string s = "t";
Filename f1 = s;
Filename f2(s);
class Filename
{
public:
Filename(std::string const &oFilename, std::string const &oBasePath = "");
Filename(char const *oFilename = NULL, char const *oBasePath = NULL);
Filename(const Filename &oSource);
virtual ~Filename(void);
void setBasePath(std::string const &oBasePath);
void setBasePath(const char *oBasePath);
const std::string &getBasePath(void) const;
std::string getBaseDir(void) const;
std::string getFileDir(void) const;
};
问题是,您的函数接收到对
FileName
的引用,但您正试图将rvalue
传递给它。这是不正确的,临时值不能绑定到左值引用
,不能将参数更改为常量引用
,也不能创建文件名
对象并传递它。不能将临时值绑定到非常量引用。请将参数更改为常量。不幸的是,此函数可能需要修改传入的对象,为什么我没有把它变成常量。至少我现在理解了这个问题,必须看看如何解决它。:)我还从intellisense中得到了一个错误,对非常量的引用的初始值必须是左值,这使它更加清晰。我现在明白问题所在了。谢谢