赋值运算符适用于不同类型的对象吗?
class A {
public:
void operator=(const B &in);
private:
int a;
};
class B {
private:
int c;
}
对不起。 发生了错误。 赋值运算符有效吗? 或者有什么办法可以实现这一点? [A 级和 B 级之间没有关系。]
void A::operator=(const B& in)
{
a = in.c;
}
非常感谢。
class A {
public:
void operator=(const B &in);
private:
int a;
};
class B {
private:
int c;
}
sorry. there happened an error. is assignment operator valid ? or is there any way to achieve this? [There is no relation between A and B class.]
void A::operator=(const B& in)
{
a = in.c;
}
Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,你可以这样做。
Yes you can do so.
这不是一个答案,但应该知道,赋值运算符的典型习惯用法是让它返回对对象类型的引用(而不是 void)并在最后返回 (*this)。 这样,您就可以链接分配者,如 a = b = c:
This isn't an answer, but one should be aware that the typical idiom for the assignment operator is to have it return a reference to the object type (rather than void) and to return (*this) at the end. This way, you can chain the assignent, as in a = b = c:
赋值运算符和参数化构造函数都可以具有任何类型的参数,并以它们想要的任何方式使用这些参数的值来初始化对象。
Both assignment operator and parameterized constructors can have parameters of any type and use these parameters' values any way they want to initialize the object.
其他人已经对此有所了解,但我将实际说明一下。 是的,您可以使用不同的类型,但请注意,除非您使用friend,否则您的类无法访问通过运算符传入的类的私有成员。
这意味着 A 将无法访问 B::c,因为它是私有的。
Others have clued in on this, but I'll actually state it. Yes you can use different types, but note that unless you use friend, your class cannot access the private members of the class it's being passed in with the operator.
Meaning A wouldn't be able to access B::c because it's private.