我創建了兩個檔案,Linkage.cpp和External.cpp.
Linkage.cpp:
#include <iostream>
void Log(int x = 5)
{
std::cout << x << "\n";
}
int main()
{
Log();
return 0;
}
External.cpp:
#include <iostream>
void Log(const char* message)
{
std::cout << message << "\n";
}
為什么我沒有收到聯結器錯誤?這兩個函式都定義在全域命名空間中,因此應該與變數一樣存在命名沖突。
uj5u.com熱心網友回復:
為什么我沒有收到聯結器錯誤?
當你寫
void Log(int x = 5)//this means that the function named Log can be called without passing
//any argument because you have provided a default argument which will be
//used in case you don't provide/pass any argument
{
//..other code here
{
以上意味著Log可以在不傳遞任何引數的情況下呼叫命名的函式,因為您提供了一個默認引數,如果您不提供/傳遞任何引數,將使用該引數。
接下來當你寫
void Log(const char* message)//this means that this versoin of the function named Log will be called only if you pass an argument of type `char*` .
{
std::cout << message << "\n";
}
上面的意思是只有當你傳遞一個 type 的引數時Log才會呼叫這個函式的版本。char*
現在當你寫道:
Log();
將使用具有默認引數的第一個版本,因為您尚未提供任何引數,因此可以使用第一個版本(因為它是可行的)并且因為必須采用引數的第二個版本是不可行的。
uj5u.com熱心網友回復:
好的,在@Retire Ninja 向我指出這一點后,我進行了實驗。
首先,注釋掉External.cpp. 現在,Log在里面宣告另一個函式,Linkage.cpp以便在這個檔案中有兩個具有相同名稱(Log)但引數不同的函式。您將意識到根據您提供的引數使用不同的Log函式,這些函式將表現得像不同的函式。
因此,與變數不同,同名意味著命名空間中的相同變數,函式也需要具有匹配的簽名。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/370232.html
上一篇:Pythondef函式賦值問題
下一篇:在熊貓累積周級別應用函式
