2015-09-04 61 views
-1

在Visual Studio 2010中,我收到錯誤C2664,說沒有從std::string到我的類Filename轉換。從std :: string到類的隱式轉換不起作用

我真的不明白爲什麼會這樣,因爲我有構造函數接受一個std::string這適用於這樣的代碼:

std::string s = "t"; 
Filename f1 = s; 
Filename f2(s); 

但是我有一個函數

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 

我的名類看起來是這樣的:

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; 

}; 
+1

您不能將臨時綁定到非const參考。將您的參數更改爲const。 – Borgleader

+0

不幸的是,這個函數可能需要修改傳入的對象,爲什麼我沒有做const。至少我現在明白了這個問題,並且必須看到如何解決它。 :) – Devolus

回答

1

問題是,你函數接收到FileName參考,但你試圖傳遞rvalue它。這是不正確的,臨時值不​​能綁定到lvalue-reference,將參數更改爲const reference,或創建FileName對象並將其傳遞。

+0

我也得到了來自intellisense的一個錯誤'對非const的引用的初始值必須是一個左值',這使得它更清晰。我現在看到了這個問題。謝謝! – Devolus

相關問題