我想將一個類的函式應用于另一個派生類的私有變數。我希望這樣可以避免多次重新定義完全相同的功能。
我在下面添加了一個示例。
#include <iostream>
class A {
public:
void print1();
void print2();
private:
int array[3] = {1, 2, 3};
};
class B: public A {
public:
void print3();
private:
int array[3] = {4, 5, 6};
};
void A::print1() {
std::cout << this->array[0] << std::endl;
}
void A::print2() {
std::cout << this->array[1] << std::endl;
}
void B::print3() {
print1();
print2();
std::cout << this->array[2] << std::endl;
}
int main() {
B b;
b.print3(); // Output = 1 2 6, I want = 4 5 6
return 0;
}
我認為也許將A類和B類中的陣列定義為公共的,所以它會被覆寫,會起作用,但這沒有任何效果。
uj5u.com熱心網友回復:
有兩種解決方案,與設計模式相關,稱為“非虛擬介面”或“模板方法”。
沒有虛擬方法:添加一個指向私有陣列的成員:
class A {
public:
A() : array(_array) {}
void print1();
void print2();
protected:
A(int array[3]) : array(array) {}
int *array;
private:
int _array[3] = {1, 2, 3};
};
class B: public A {
public:
B() : A(_array) {}
void print3();
private:
int _array[3] = {4, 5, 6};
};
或者添加一個虛擬方法,它將回傳指標:
class A {
public:
void print1();
void print2();
protected:
virtual int *array() { return _array; };
private:
int _array[3] = {1, 2, 3};
};
class B: public A {
public:
void print3();
protected:
virtual int *array() { return _array; };
private:
int _array[3] = {4, 5, 6};
};
在第二個解決方案中,使用array()而不是array在方法(std::cout << this->array()[0] << std::endl;等)中。
uj5u.com熱心網友回復:
如果print1and的實作print2必須在基類中,那么您需要對與物件實體關聯的陣列進行某種形式的多型訪問。
#include <iostream>
class A {
public:
void print1();
void print2();
private:
virtual const int* getArray() const { return array; };
int array[3] = {1, 2, 3};
};
class B: public A {
public:
void print3();
private:
virtual const int* getArray() const { return array; };
int array[3] = {4, 5, 6};
};
void A::print1() {
std::cout << this->getArray()[0] << std::endl;
}
void A::print2() {
std::cout << this->getArray()[1] << std::endl;
}
void B::print3() {
print1();
print2();
std::cout << this->getArray()[2] << std::endl;
}
int main() {
B b;
b.print3(); // Outputs 4 5 6
return 0;
}
uj5u.com熱心網友回復:
繼承不是這樣作業的,你接近得到它,但你的設計需要一個小的改變。您需要做的是更改您的print1和print2功能,以接收您要列印的引數:
class A {
public:
void print1(int num);
...
private:
int array[3] = {1, 2, 3};
};
void A::print1(int num) {
std::cout << num << std::endl;
}
然后你用你感興趣的呼叫print1andprint2函式:int
void B::print3() {
print1(array[0]);
print2(array[1]);
std::cout << this->array[2] << std::endl;
}
這將B使用存盤在 "override" 中的值呼叫類中的這些函式array,并且您將獲得所需的輸出:
int main() {
B b;
b.print3(); // Output = 4 5 6
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/524182.html
標籤:C 班级遗产
上一篇:添加列Heroku資料庫
