我想設計一個類,它提供了一個函數,根據它的某個屬性來執行某些操作。我也想做同樣的過程,但有了另一個值,這就是爲什麼我創建了派生類並修改了屬性。C++繼承與不使用getter的const成員
首先,我創建了一個靜態屬性,因爲該值不取決於每個對象,而是取決於類本身。或者,我不能繼承一個靜態屬性並修改每個類的一個。
然後,我決定把我的屬性在const中能夠使用繼承。我做了一個簡單的程序來向你展示我的問題。在這裏,我希望foo顯示調用該方法的對象的值,而不是父級的值。另外,我不想使用getter,因爲我會在我的方法中多次使用變量,這是用於圖像處理的。
#include <iostream>
// Compile it with
// g++ -o child_test child_test.cpp -std=c++11
class Parent{
public:
Parent() {}
virtual void foo(){
printf("%d\n", this->bar);
}
private:
const int bar = 0;
};
class Child : public Parent{
public:
Child() : Parent() {}
private:
const int bar = 10;
};
int main(){
Parent * p = new Parent();
p->foo(); // Output : 0
Child * c = new Child();
c->foo(); // Output : 0 ? How could it be 10
Parent * cp;
cp = new Child();
cp->foo(); // Output : 0 ? How could it be 10
}
好吧,所以我需要在構造函數中實例化它?否則,電話不會聯絡。這是可能的靜態變量? –