菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
343
0

In c++ access control works on per-class basis not on per-object basis.

原创
05/13 14:22
阅读数 69763
#ifndef MYTIME_H 
#define MYTIME_H 
  
class MyTime 
{ 
private: 
    int m_hour; 
    int m_minute; 
public: 
    MyTime(int hour,int minute=0); 
    ~MyTime(); 
  
    MyTime operator+(const MyTime & time) const; 
    void Show(); 
  
    //int GetHour() const; 
    //int GetMinute() const; 
}; 
  
#endif 
#include "MyTime.h" 
#include <iostream> 
  
MyTime::MyTime(int hour,int minute) 
{ 
    m_hour=hour; 
    m_minute=minute; 
}; 
  
MyTime::~MyTime() 
{}; 
  
MyTime MyTime::operator+(const MyTime & time) const
{ 
    //MyTime sum 
    //  =MyTime( 
    //      time.GetHour()+m_hour+(time.GetMinute()+m_minute)/60, 
    //      (time.GetMinute()+m_minute)%60 
    //  ); 
    //return sum; 
    MyTime sum 
        =MyTime( 
            time.m_hour+m_hour+(time.m_minute+m_minute)/60, 
            (time.m_minute+m_minute)%60 
        ); 
    return sum; 
}; 
  
void MyTime::Show() 
{ 
    std::cout<<"Hour = "<<m_hour<<" , Minute = "<<m_minute<<std::endl; 
}; 
  
//int MyTime::GetHour() const 
//{ 
//  return m_hour; 
//}; 
//int MyTime::GetMinute() const 
//{ 
//  return m_minute; 
//}; 
Because that's how it works in c++.In c++ access control works on
per-class basis not on per-object basis.
Access control in c++ is implemented as a static,compile-time feature.I think it is rather obvious that it is not really possible to implement any meaningful per-object access control at compile time.only per-class control can be implemented that way.
some hints of per-object control are present in protected access specification,which is why it even has its own dedicated chapter in the standard(11.5).But still any per-object features described there are rather rudimentary.Again,access control in c++ is meant to work on per-class basis.
Your "it is not really possible to implement any meaningful per-object access control at compile time". Why not? In void X::f(X&x), the compiler is easily capable of distinguishing this->a and x.a. It's not (always) possible for the compiler to know that *this and x are actually the same object if x.f(x) is invoked, but I could very well see a language designer find this OK.

发表评论

0/200
343 点赞
0 评论
收藏