Home  >  Q&A  >  body text

c++ - 构造函数为啥能访问参数的私有数据成员

对于c++ private数据成员访问的问题: 
class MyClass
{
public:
    MyClass(const char* str = NULL)
    {
        if(str == NULL)
        {
            m_data = new char[1];
            *m_data = '\0';
        }
        else
        {
            int len = strlen(str);
            m_data = new char[len + 1];
            strcpy(m_data,str);
        }
    }

    MyClass(const MyClass &other)
    {
        printf("%s\n" , other.m_data );
    }

    ~MyClass(void)
    {
        delete [] m_data;
    }
private:
    char *m_data;
};


MyClass* tmp = new MyClass("a");
MyClass tmp1 = *tmp; // a

上述代码的拷贝构造函数可以访问到参数的private数据成员,这个怎么理解?

后续又添加了个测试函数,发现还是可以访问

class MyClass1
{
public:
    MyClass1(const char* str = NULL);
    MyClass1(const MyClass1 &other);
    ~MyClass1(void);

    void TestPri(const MyClass1 &other);

private:
    char *m_data;
};

MyClass1::MyClass1(const char* str)
{
    if(str == NULL)
    {
        m_data = new char[1];
        *m_data = '\0';
    }
    else
    {
        int len = strlen(str);
        m_data = new char[len + 1];
        strcpy(m_data,str);
    }
}

MyClass1::MyClass1(const MyClass1 &other)
{
    printf("%s\n" , other.m_data );
}

MyClass1::~MyClass1(void)
{
    delete [] m_data;
}

void MyClass1::TestPri(const MyClass1 &other)
{
    printf("%s\n" , other.m_data );
}
MyClass1* tmp = new MyClass1("a");
MyClass1 tmp1 = *tmp; // a
MyClass1 tmp2;
tmp2.TestPri(*tmp); // a

求解答

PHPzPHPz2764 days ago598

reply all(1)I'll reply

  • 阿神

    阿神2017-04-17 14:37:49

    Access control permissions are based on classes, not objects. For this reason, member functions can access private member variables of objects of this class, but cannot access private members of objects of other classes. There is a similar question here: http://stackoverflow.com/ques...

    reply
    0
  • Cancelreply