我在 Visual Studio 2022 中有以下 C 代碼示例:
#include<iostream>
#include<string>
employee get_employee() {
employee out = { 1, "John"};
return out;
}
class employee {
public:
int id;
std::string name;
};
int main() {
std::cout << get_employee().name;
return 0;
}
但是當我運行它時,我得到編譯器的抱怨get_employee(),特別是“只有回傳型別不同的函式不能被多載”。
但是,如果我的代碼中沒有其他定義
,為什么會這樣做呢?get_employee()
我知道在定義類本身之前我無法創建類的實體,并且在類get_employee()定義下方移動employee定義確實解決了這個問題,但它并沒有解釋為什么編譯器會說“僅通過回傳型別不同的函式不能'不要多載”而不是說你“在定義類本身之前不能創建一個類的實體”,我想知道為什么。
uj5u.com熱心網友回復:
這里的問題相當簡單。您在定義它的含義之前嘗試使用它。 employee將您的定義移到 的定義employee之前get_employee。
#include<iostream>
#include<string>
class employee {
public:
int id;
std::string name;
};
employee get_employee() {
employee out = { 1, "John"};
return out;
}
int main() {
std::cout << get_employee().name;
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/441851.html
