私有变量可以从同一类型的另一个对象访问? [英] A private variable can be accessed from another object of the same type?
本文介绍了私有变量可以从同一类型的另一个对象访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C ++类的私有成员设计为对其他类实例不可见。我很困惑,因为私人会员可以访问,如下所示!
Private members of a C++ class are designed to be invisible to other class instances. I'm confused since private members can be accessed as shown below! Can anyone explain it to me?
以下是我的代码:
#include <iostream>
using namespace std;
class Person
{
private:
char* name;
int age;
public:
Person(char* nameTemp, int ageTemp)
{
name = new char[strlen(nameTemp) + 1];
strcpy(name, nameTemp);
age = ageTemp;
}
~Person()
{
if(name != NULL)
delete[] name;
name = NULL;
}
bool Compare(Person& p)
{
//p can access the private param: p
//this is where confused me
if(this->age < p.age) return false;
return true;
}
};
int main()
{
Person p("Hello, world!", 23);
return 0;
}
推荐答案
它的所有类实例的私有属性,至少在C ++中。
Methods of a class can access its private attributes throughout all class instances, at least in C++.
这篇关于私有变量可以从同一类型的另一个对象访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文