类成员函数可以访问相同类对象的私有对象
2013-03-19 17:32
393 查看
今天在学习c++ copying函数的时候,了解到这个问题:类成员函数可以访问相同类对象的私有对象;
下面这个例子是很好的copying函数,有很多细节。
实例如下:
class Customer
{
public:
Customer(const Customer& c):
_name(c._name)
{
}
Customer& operator=(const Customer& c)
{
_name = c._name ;
return *this ;
}
private:
std::string _name ;
};
class PriorityCustomer : public Customer
{
public:
PriorityCustomer(const PriorityCustomer& pc):
Customer(pc),
_priority(pc._priority)
{
}
PriorityCustomer& operator=(const PriorityCustomer& pc)
{
Customer::operator=(pc);
_priority = pc._priority;
return *this ;
}
private:
int _priority ;
};
1. 子类实现copying函数一定要调用父类的copying函数,否则会调用一个父类的默认copying函数,导致问题;
2. 可以用子类对象构造父类;
3. 这个例子说明了另外一个问题,类成员函数可以访问相同类对象的私有成员;
下面这个例子是很好的copying函数,有很多细节。
实例如下:
class Customer
{
public:
Customer(const Customer& c):
_name(c._name)
{
}
Customer& operator=(const Customer& c)
{
_name = c._name ;
return *this ;
}
private:
std::string _name ;
};
class PriorityCustomer : public Customer
{
public:
PriorityCustomer(const PriorityCustomer& pc):
Customer(pc),
_priority(pc._priority)
{
}
PriorityCustomer& operator=(const PriorityCustomer& pc)
{
Customer::operator=(pc);
_priority = pc._priority;
return *this ;
}
private:
int _priority ;
};
1. 子类实现copying函数一定要调用父类的copying函数,否则会调用一个父类的默认copying函数,导致问题;
2. 可以用子类对象构造父类;
3. 这个例子说明了另外一个问题,类成员函数可以访问相同类对象的私有成员;
相关文章推荐
- C/C++—— 除了用类成员函数访问类私有成员变量外,还可以通过类对象地址来直接访问和修改类的私有成员变量
- C++中类的访问权限针对的是类而不是对象!(为什么类中的函数可以访问对象的私有成员?)
- 因为成员函数属于同一个类的所有对象,所以在成员函数内可以访问同类其他对象的私有成员是合理的
- 同一个类的不同对象,对象的成员函数可以互相访问各自对象的私有变量和私有成员函数
- 关于类成员函数中访问同类对象的私有成员
- 关于类成员函数中访问同类对象的私有成员
- 关于类成员函数中访问同类对象的私有成员
- C++在类的成员函数中,允许直接访问该类的成员对象的私有成员变量
- friend函数访问2个类的对象的私有成员
- C++本类可以访问本身类的私有成员(即拷贝构造函数可以访问本身对象的私有成员)
- C++中的private:类型相同的两个对象,是否可以访问对方的private成员?
- 为什么一个对象调用的类方法可以访问该类其他对象的私有成员
- 关于类成员函数中访问同类对象的私有成员
- C++在类的成员函数中,允许直接访问该类的成员对象的私有成员变量
- 关于类成员函数中访问同类对象的私有成员
- 关于类成员函数中访问同类对象的私有成员
- 同一个类不同对象,可以互相访问对方的私有成员而不通过get()或set()
- 测试在类的内部是否可以访问对象的私有成员
- 理解类级别的访问控制权限——类的成员函数可以访问该类所有对象的私有成员
- 静态成员函数中不允许引用类的非静态成员,但可以访问对象中的非静态成员