作者ric2k1 (Ric)
看板EE_DSnP
标题Re: [问题]关於 static function
时间Tue Jan 1 21:49:11 2008
static data member 一定要在 global scope 被 initialized.
因为它必须在任何 class object 被 construct 之前就被 initialized.
所以必须要在任何 .cpp 档不属於任何 function 的 global scope:
unsigned ModInt::_modulus = 0;
注意, 不要重复写 "static" 喔!
※ 引述《ricky770927 (ricky)》之铭言:
: 我写:
: #include<iostream>
: using namespace std;
: class ModInt
: {
: public:
: ModInt(const int& i){_number=i;};
: static void setMod(unsigned i){_modulus=i;}
: private:
: unsigned _number;
: static unsigned _modulus;
: };
: void main()
: {
: int mod;
: cout<<"Please enter the modulus (> 0): "<<endl;
: cin>>mod;
: while(mod<=0)
: {
: cout<<"Please enter the modulus (> 0): "<<endl;
: cin>>mod;
: }
: ModInt a(5);
: ModInt::setMod(mod);
: }
: 在build时出错
: HW9.OBJ : error LNK2001: unresolved external symbol "private: static unsigned int ModInt::_modulus" (?_modulus@ModInt@@0IA)
: Debug/HW9.exe : fatal error LNK1120: 1 unresolved externals
: 到底是哪里有问题?
: 请帮我解答一下 谢谢!!
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 59.121.132.105
1F:推 Davefox:感动,顺便也解了我的问题 01/01 22:37
2F:推 ricky770927:了解了!!谢谢 01/01 23:49