[英]Does C++ calls member object 's overloaded operator?
#include <stdio.h>
class InnerOne {
int m_iDummy;
public:
InnerOne(int iDummy) {
m_iDummy=iDummy;
}
InnerOne& operator=(InnerOne &obj) {
printf("In InnerOne Operator=\n");
m_iDummy = obj.m_iDummy;
return *this;
}
};
class OuterOne {
InnerOne m_innerOne;
public:
OuterOne(int iVal) : m_innerOne(iVal) {
}
};
int main() {
OuterOne a(1);
OuterOne b(2);
a = b;
return 1;
}
Will InnerOne 's operator = get called? InnerOne 的 operator = 会被调用吗? If yes then how and why?
如果是,那么如何以及为什么?
Yes.是的。 The automatically generated assignment operator for
OuterOne
will call the assignment operator of InnerOne
. OuterOne 自动生成的赋值运算符将调用
OuterOne
的赋值运算InnerOne
。
Yes.是的。 The compiler generated copy-assignment for
OuterOne
will invoke the operator=
for InnerOne
.编译器为
InnerOne
生成的复制赋值将为OuterOne
调用operator=
。
As a sidenote, its better if you write InnerOne
copy-assignment as:作为旁注,如果您将
InnerOne
复制分配写为:
InnerOne& operator=(const InnerOne &obj)
//^^^^ add this!
const
is necessary, or else your code wouldn't work for the following: const
是必需的,否则您的代码将不适用于以下情况:
const InnerOne x(10);
InnerOne y(10);
y = x; //compilation error - if you use your code
See the error here: http://www.ideone.com/YMTJS在此处查看错误: http://www.ideone.com/YMTJS
And once you add const
as I suggested, it'll compile.一旦你按照我的建议添加了
const
,它就会编译。 See this: http://www.ideone.com/xj06z看到这个: http://www.ideone.com/xj06z
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.