我有兩個類,A 類,B 類,B 類中有一個靜態函式,如下所示:
class A {
public:
void method(){ B::method(); }
};
class B {
public:
static int method() {
cout << "method of b" << endl;
}
};
int main()
{
class A a;
a.method();
}
這段代碼構建錯誤,因為在A類中,B沒有被宣告,但我希望A類早于B類定義,我該怎么辦?我認為它可能需要預先宣告,但似乎不是這個原因......
uj5u.com熱心網友回復:
看一下修改后的代碼。行內注釋解釋了更改:
class A {
public:
// only declare the method
void method();
// Do NOT define it here:
// { B::method(); }
};
class B {
public:
static int method() {
std::cout << "method of b" << std::endl;
return 0;
}
};
// and now, as B implementation is visible, you can use it.
// To do this, you can define the previously declared method:
void A::method() { B::method(); }
int main()
{
class A a;
a.method();
}
提示:請永遠不要使用 using namespace std
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/379267.html
下一篇:在類函式中獲取API
