2014-09-03 53 views
8

這裏是我的代碼:不應該char *隱式轉換爲std :: string?

#include <iostream> 
using namespace std; 

struct ST {}; 

bool operator==(const struct ST *s1, const string &s2) { 
    return true; 
} 

int main() { 
    struct ST *st = new ST(); 
    const char *p = "abc"; 

    if (st == p) { 
     return 0; 
    } 

    return 1; 
} 

我得到編譯錯誤:

prog.cpp:14:12: error: comparison between distinct pointer types ‘ST*’ and ‘const char*’ lacks a cast [-fpermissive] 
    if (st == p) { 
      ^

我不知道爲什麼,從字符*串隱式轉換不會在這裏工作?

UPDATE 安東的回答是有道理的,我更新的代碼:

#include <string> 
using namespace std; 

struct ST {}; 

bool operator==(const struct ST s1, const string &s2) { 
    return true; 
} 

int main() { 
    struct ST st; 
    const char *p = "abc"; 

    if (st == p) { 
     return 0; 
    } 

    return 1; 
} 

現在它編譯。

+3

比較不同類型的指針。你的重載操作符不會被調用。 – 101010 2014-09-03 15:41:48

+2

與你的問題無關,但'#include '在這裏不是必需的。 '#include '是。 – 2014-09-03 15:54:47

回答

17

§13.3.1.2 Operators in expressions [over.match.oper]狀態:

If no operand of an operator in an expression has a type that is a class or an enumeration, the operator is assumed to be a built-in operator and interpreted according to Clause 5.

這正是你的情況:operator==的參數爲指針,因此它被認爲是內置和編譯器也不會去尋找可能的過載。

0

絕對不是。

首先,您正嘗試使用指針代替參考。指針和引用之間的任何相似性都是實現細節。記住座右銘:「實施無關緊要!」

接下來,更直接的問題,std :: string和char *是完全不同的,即使它們用來表示相同的東西。它們之間的轉換故意難以互換地使用它們。

+5

我認爲你已經錯過了,雖然'st == p'被拒絕,'operator ==(st,p)'完全有效,並且具有OP希望用'st == p'得到的確切行爲。 'const string&'可以從'string'類型的臨時對象中初始化,'const'類型的臨時類型可以由'const char *'構造。 – hvd 2014-09-03 16:05:42

相關問題