gpt4 book ai didi

C++ 类访问级别

转载 作者:可可西里 更新时间:2023-11-01 16:38:38 25 4
gpt4 key购买 nike

假设我有两个类(class)。一个叫做点:

class Point{
public:
Point(): x_(0), y_(0) {}
protected:
int x_, y_;
};

然后我有另一个类,它派生自 Point:

class Point3D : public Point {
public:
Point3D(): Point(), z_(0){}
double distance(Point3D pt, Point base) const;
protected:
int z_;
};

double Point3D::distance(Point3D pt, Point base) const
{
int dist_x, dist_y;
dist_x = base.x_ - x_;
dist_y = base.y_ - y_;

return sqrt(dist_x * dist_x +
dist_y * dist_y);
}

然后我得到类似这样的错误:base.x_ is protected within this context。但是 Point3D 对 Point 的访问级别是 public,加上 Point 中的 x_ 数据成员是 protected 。所以它应该没有错误,对吧?有人可以帮我解决这个问题吗?

最佳答案

But the access level of Point3D to Point is public

这并不完全正确。只有通过派生类指针/引用访问基类的 protected 成员时,派生类才能访问它们。

double Point3D::distance(Point3D pt, Point base) const
{
int dist_x, dist_y;
dist_x = base.x_ - x_; // x_ is same as this->x_. Hence it is OK.
// base is not a Point3D. Hence base.x_ is not OK.
dist_y = base.y_ - y_;

return sqrt(dist_x * dist_x +
dist_y * dist_y);
}

允许通过基类指针/引用访问基类的protected 成员将允许您以导致意外后果的方式更改对象。

假设你有:

class Base
{
protected:
int data;
};

class Derived1 : public Base
{
void foo(Base& b)
{
b.data = 10; // Not OK. If this were OK ... what would happen?
}
};

class Derived2 : public Base
{
};

int main()
{
Derived1 d1;
Derived2 d2;
d1.foo(d2);
}

如果

       b.data = 10;

Derived1::foo 中被允许,您可以修改 d2 的状态,Derived2 的实例 派生 1。这种后门修改不是理想的行为。

关于C++ 类访问级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40517677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com