#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" #includeMyTime::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 = "< <<" , 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.