c ++对对象使用=运算符

c++ using the = operator with objects

在 C++ 中一直让我感到困惑的一个操作是 operator= 如何与对象交互。 我不确定在执行这样的程序时幕后到底发生了什么:

class ObjectType {
    private:
        int variable;
    public:
        ObjectType(int v) {
            variable = v;
        }
};

int main() {
    ObjectType object1(10);
    ObjectType object2(15);

    object1 = object2;

    return 0;
}

根据我的理解,它使第一个对象中的所有成员变量都等于第二个对象中相应的成员变量。在这种情况下,object1 的 "variable" 现在等于 15,但我不确定。

如有详细说明,将不胜感激。

当您键入 object1 = object2; 时,它会调用 = 运算符重载函数,如果 operator overloading function 不是 assignment operator 定义,然后编译器为我们做 by-default,编译器只是做一个 member-wise copyone object to 另一个对象.

这是基本代码:

class ObjectType {
        private:
                int variable;
        public:
                ObjectType(int v) {
                        variable = v;
                }
                void operator () (int n1){ /** () operator overloaded function if needed **/
                        variable = n1;
                }
};

int main() {
        ObjectType object1(10);//parameterized constructor will be called  
        ObjectType object2(15);
     /** use case when () operator overloaded function will be called
         ObjecType object1;
         object1(10);// invokes () overloaded function 
     **/

        object1 = object2;/** if = operator overloaded function is not defined then consider default one provided by compiler */
        return 0;
}