gpt4 book ai didi

c++ - 运算符重载内部调用转换

转载 作者:搜寻专家 更新时间:2023-10-31 01:53:12 25 4
gpt4 key购买 nike

如果有类

class complex
{
private:
float real,imag;
public:
complex operator +(complex c)
{
complex t;
t.real=real+c.real;
t.imag=imag+c.imag;
return t;
}

如果我们通过以下方式调用重载运算符,则在 main 中

c3=c1+c2;

然后编译器内部转换为 c3=c1.operator+(c2)

类似地,在运算符重载的类似示例中,= 的链接

class circle
{
private:
int radius;
float x,y;
public:
circle()
{}
circle(int rr,float xx,float yy)
{
radius=rr;
x=xx;
y=yy;
}
circle& operator=(const circle& c)
{
cout<<endl<<"assignment operator invoked";
radius=c.radius;
x=c.x;
y=c.y;
return *this;
}
int main()
{
circle c1 (10,2.5,2.5);
circle c2,c3;
c3=c2=c1;
c1.showdata();
c2.showdata();
c3.showdata();
return 0;
}

Overloaded = to operator 将首先为 c2=c1 调用 2 次,然后为 c3=c2 调用。那么编译器将如何使用其函数原型(prototype)处理 c2=c1 ?编译器将如何在内部转换这个重载的 operator = call ?(请引用上面的附加示例)谁的私有(private)字段将被访问并返回到一个对象值??

最佳答案

c3=c2=c1;

被类似地评估为

c3.operator=(c2.operator=(c1))

c2.operator=(c1) 在分配 c1 后返回对 c2 的引用。

请注意,对于您的类,您不需要重载 operator =,因为编译器生成的操作完全相同

如果这样做,您应该遵守三原则 - 并且还要添加析构函数和复制构造函数。但是,同样,您的类(class)也不需要。

关于c++ - 运算符重载内部调用转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11467955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com