![](/img/trans.png)
[英]C++ How to create base class which creates derived class object, and access private members of base class?
[英]C++ code that cannot access private members of a class using derived class
我目前有下面的代碼,當實例化 Solid 類型的 object 時,我試圖將數據成員 x、y 和 z 初始化為 0。 第 25、26 和 27 行包含錯誤,我將如何重寫這些行以訪問 x 和 y 成員並將它們設置為 0?
編輯1:我在下面寫出了我的代碼。
編輯 2:為了清楚起見,唯一可以更改的代碼行是包含錯誤的行。 應重寫派生的 class 以訪問私有數據成員。
class Shape
{
private:
int x, y;
protected:
string _type;
public:
Shape() { x = y = 0; }
Shape(int a, int b) { x = a; y = b; }
string type() { return _type; }
void stype(string val) { _type + val; }
int getx() { return x; }
int gety() { return y; }
};
class Solid : public Shape
{
int z;
public:
Solid() { x = y = z = 0; } // errors
Solid(int a, int b, int c) { x = a; y = b; z = c; } //
int Volume() { return x * y * z; } //
};
int main()
{
Solid ob1;
return 0;
}
繼承的 class 無法訪問父級的私有屬性。 它可以訪問他的受保護屬性,因此您可以將變量移至受保護。 另一種選擇是使用設置器 function(如 getX)並使用它們。
編輯:僅更改相關錯誤行:
Solid():Shape(0,0) { this->z = 0; }
Solid(int a, int b, int c):Shape(a,b) { this->z = c; }
int Volume() { return this->getx() * this->get.y * this->z; }
當您創建Solid
object 時,您還可以使用所需的值調用Shape
的 c'tor。 這是在創建新的繼承對象時初始化x, y
值的正確方法。 對於第三行計算,您應該使用getx()
和gety()
函數。 如前所述,關鍵是要了解 Solid object 不能直接訪問 x 和 y
您不能直接繼承父 class 的私有成員。 您可以在派生類(子類)構造函數中使用它的構造函數,雖然它很酷,但我不使用這種方式。 有關訪問說明符的一些信息(您聲明的 inheritance 的類型):
再次注意,您的父 class 的私有成員不會被繼承。 這應該可以解決問題:更改:
private:
int x, y;
進入:
protected:
int x, y;
使用父 class 構造函數應該如下所示:
class Solid : public Shape
{
private://doesn't matter, just for the aesthetics
int x;
int y;
int z;
public:
Solid() {
Shape();
z = 0; } // errors
直接的方法是(您的代碼添加了 x,y 作為類的屬性):
class Solid : public Shape
{
private://doesn't matter, just for the aesthetics
int x;
int y;
int z;
public:
Solid() {x=y=z = 0; } // errors
您不能訪問基礎 class 的私有成員,而本練習的重點是您不需要 - 不是說您應該想出一種方法來做到這一點。
您的默認構造函數應該只設置它自己的成員 - Shape
的默認構造函數會處理它自己的成員:
Solid() { z = 0; }
或(首選方法,實際上是初始化而不是賦值)
Solid() :z(0) {}
另一個構造函數應該初始化基礎,然后是z
:
Solid(int a, int b, int c) : Shape(a,b), z(c){}
和Volume
應該使用提供的訪問器:
int Volume() { return getx() * gety() * z; }
私有數據成員永遠不會在任何類型的 inheritance 中繼承。 因此名稱私有,但有趣的是,您可以在這里使用朋友 class 概念,甚至現在繼承私有數據成員,
請嘗試運行以下代碼:
#include <bits/stdc++.h>
using namespace std;
class Shape
{
private:
int x, y;
protected:
string _type;
public:
Shape() { x = y = 0; }
Shape(int a, int b) { x = a; y = b; }
string type() { return _type; }
void stype(string val) { _type + val; }
int getx() { return x; }
int gety() { return y; }
friend class Solid;
};
class Solid : public Shape
{
int z;
public:
Solid() { x = y = z = 0; } // errors
Solid(int a, int b, int c) { x = a; y = b; z = c; } //
int Volume() { return x * y * z; } //
};
int main()
{
Solid ob1;
return 0;
}
現在您也可以在繼承的 class 中訪問 x,y,因為您將 class 聲明為實體 class 的朋友。
希望這能回答你的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.