ใน C ++ มีเหตุผลใดที่จะไม่เข้าถึงตัวแปรสมาชิกแบบคงที่ผ่านอินสแตนซ์ของคลาสหรือไม่ ฉันรู้ว่า Java ขมวดคิ้วกับเรื่องนี้และสงสัยว่ามันสำคัญกับ C ++ หรือไม่ ตัวอย่าง:
class Foo {
static const int ZERO = 0;
static const int ONE = 1;
...
};
void bar(const Foo& inst) {
// is this ok?
int val1 = inst.ZERO;
// or should I prefer:
int val2 = Foo::ZERO
...
};
ฉันมีคำถามที่สองโบนัส ถ้าฉันประกาศ static double ฉันต้องกำหนดมันที่ไหนสักแห่งและคำจำกัดความนั้นจะต้องทำซ้ำประเภทนั้น เหตุใดจึงต้องพิมพ์ซ้ำ? ตัวอย่างเช่น:
In a header:
class Foo {
static const double d;
};
In a source file:
const double Foo::d = 42;
เหตุใดฉันจึงต้องทำซ้ำส่วน "const double" ในไฟล์ cpp ของฉัน