![](/img/trans.png)
[英]Return type of CallStaticBooleanMethodV does not match Java method signature - Calling Java method from C/C++
[英]C++ identical method signature but different return type
我看過以下代碼:
template <class T>
class Type {
public:
Type() {}
T& operator=(const T& rhs) {value() = rhs; return value();}
T& value() {return m_value;}
T value() const {return m_value;}
private:
T m_value;
};
為什么編譯器不抱怨
T& value() {return m_value;}
T value() const {return m_value;}
以及如何知道調用哪一個?
這兩個功能實際上並不相同。 只有第二個函數被聲明為const
成員函數。 如果調用該成員的對象是const
,則使用后一個選項。 如果對象是非const
,則使用第一個選項。
例:
void any_func(const Type *t)
{
something = t->value(); //second `const` version used
}
void any_func2(Type *t)
{
something = t->value(); //first non-`const` version used
}
如果這兩個函數被宣布不const
或兩者被宣布為const
,編譯器會 (應,反正)抱怨。
為什么編譯器不抱怨
因為const
計算不同的函數簽名。 你假設函數簽名是相同的是錯誤的。
標記為const
將為Type<T>
任何const
實例或引用調用。
以及如何知道調用哪一個?
在函數中放置一個cout
語句並測試以下情況:
template <class T>
class Type {
public:
Type() {}
T& operator=(const T& rhs) {value() = rhs; return value();}
T& value() {
std::cout << "non const version" << std endl;
return m_value;
}
T value() const {
std::cout << "const version" << std endl;
return m_value;
}
private:
T m_value;
};
int main() {
Type<int> t;
t.value();
Type<int> rt = t;
rt.value();
Type<int>* pt = &t;
pt->value();
const Type<int> ct;
ct.value();
const Type<int>& crt = t;
crt.value();
const Type<int>* pct = &t;
pct->value();
}
賦值運算符將調用非const版本。
const版本應該更好看
const T& value() const {
std::cout << "const version" << std endl;
return m_value;
}
因為您不能總是依賴RVO(返回值優化),並且可能會采用額外的副本(特別是對於較舊的編譯器實現)。
另請注意賦值運算符應返回對當前實例的引用:
Type& operator=(const T& rhs) {value() = rhs; return *this;}
關於功能解析優先級的幾個詞。 編譯器通過以下方式區分const /非const函數:
如果一個類只有const函數和給定的名稱和參數列表,那么它將被調用為常量和非常量對象。 在調用此函數之后,對象將“假定”constness(即使它不是const),這意味着該函數只能調用其他const函數。
如果一個類只有非const函數,那么它將被調用非const對象。 嘗試為const對象調用此函數將導致編譯錯誤。
如果一個類有兩個可用的函數,const版本將用於const對象,非const版本將用於非const對象。
感謝@owacoder將我的注意力集中在描述中的初始混音上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.