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;
}
对不起。发生了错误。赋值运算符有效吗?或者有什么办法可以做到这一点?[A类和B类之间没有关系。]
void A::operator=(const B& in)
{
a = in.c;
}
非常感谢。
是的,你可以这样做。
#include <iostream>
using namespace std;
class B {
public:
B() : y(1) {}
int getY() const { return y; }
private:
int y;
};
class A {
public:
A() : x(0) {}
void operator=(const B &in) {
x = in.getY();
}
void display() { cout << x << endl; }
private:
int x;
};
int main() {
A a;
B b;
a = b;
a.display();
}
这不是一个答案,但应该知道赋值运算符的典型习惯用法是让它返回对对象类型的引用(而不是 void)并在最后返回 (*this)。这样,您可以链接分配,如 a = b = c:
A& operator=(const A& other)
{
// manage any deep copy issues here
return *this;
}
赋值运算符和参数化构造函数都可以具有任何类型的参数,并以任何他们想要初始化对象的方式使用这些参数的值。
其他人对此有所了解,但我实际上会陈述它。是的,您可以使用不同的类型,但请注意,除非您使用朋友,否则您的类无法访问通过运算符传入的类的私有成员。
这意味着 A 将无法访问 B::c 因为它是私有的。