C++中的private:类型相同的两个对象,是否可以访问对方的private成员?

28 篇文章 0 订阅
27 篇文章 2 订阅

下面的代码,为什么可以编译通过?

class Point{
public:
   Point(Point & p);
private:
    int x;
}
Point::Point(Point & p){
   x = p.x;
}

Point::Point(Point & p)函数体中的语句“x = p.x”,为什么可以正常编译?

一、先看来自ISO/IEC 14882(C++ 98年标准),中的一段话
A member of a class can be
— private; that is, its name can be used only by members and friends of the class in which it is declared.
— protected; that is, its name can be used only by members and friends of the class in which it is declared, and by members and friends of classes derived from this class (see 11.5).
— public; that is, its name can be used anywhere without access restriction.

由此段文字可知,类的访问控制是针对类,而不是针对对象的。

二、可以从以下角度解释
1. 从实现的角度看:
在静态编译期,编译器无法判断指针(或引用)是否指向(或引用)了“自己(this)”。
例:void foo(Base & b)
编译器怎么能知道&b是否是this呢?

如果仅仅从字面上要求私有成员必须要以this访问,就太过严苛了。

2.从封装的角度看:
对于访问控制而言,我们关心的是模块信息隐藏,这是一个代码级静态概念,它保证了模块实现的改变不会影响到其它模块。C++中,模块的实现主要就是类,而不是运行时的“对象”,因此,从这个角度来看,对象级别访问控制,没有什么实际意义。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ 类的对象可以直接作为类的成员变量,这种做法被称为对象成员对象成员本质上就是一个类对象,可以在另一个类声明和定义,就像声明和定义其他数据成员一样。 以下是一个使用对象成员的示例: ```c++ class Point { public: Point(int x, int y) : x(x), y(y) {} int getX() const { return x; } int getY() const { return y; } private: int x; int y; }; class Circle { public: Circle(int radius, int x, int y) : radius(radius), center(x, y) {} int getRadius() const { return radius; } Point getCenter() const { return center; } private: int radius; Point center; }; int main() { Circle c(5, 10, 20); std::cout << "Radius: " << c.getRadius() << std::endl; std::cout << "Center: (" << c.getCenter().getX() << ", " << c.getCenter().getY() << ")" << std::endl; return 0; } ``` 在上面的示例,`Circle` 类包含了一个 `Point` 类型对象成员 `center`。构造函数使用初始化列表来初始化对象成员,可以看到在 `getCenter()` 方法返回了 `center` 对象。这种方式可以将多个类组合在一起,从而实现更加复杂的数据结构和功能。 需要注意的是,对象成员的构造函数会在外部类的构造函数被调用,因此需要确保对象成员的构造函数在外部类的构造函数之前被调用。同时,对象成员也需要在外部类的析构函数被销毁,因此需要确保对象成员的析构函数在外部类的析构函数之后被调用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值