为什么私有值的obj可以被类实例改变? [英] why private value of the obj can be changed by class instance?

查看:145
本文介绍了为什么私有值的obj可以被类实例改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
using namespace std;

class A
{
    private:
        int value;
    public:
        A(int init):value(init){}
        void changevalue(A &a){a.value = 100;}//why a's value can be changed?
        void printvalue(){cout << value << endl;}
};

int main(int argc , char *argv[])
{
    A a(2);
    A b(3);

    a.changevalue(b);
    b.printvalue();

    return 0;
}

a 类,具有名为的私有值,但为什么可以更改此私有值?是参数列表包含在类的范围内吗?

a is an instance of A class,with a private value named value,but why this private value can be changed? Is that the parameter list included in the scope of class?

推荐答案

因为类访问说明符适用于每个类基础而不是每个对象基础。

Because class access specifier apply on per class basis and not per object basis.

您可以在类函数中修改相同类型的对象。实例是拷贝构造函数和拷贝赋值运算符。

You can always modify the same type of object inside the class functions.Usual examples are copy constructor and copy assignment operator.

这篇关于为什么私有值的obj可以被类实例改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆