C++ C++;重载运算符=获取右侧和左侧重载

C++ C++;重载运算符=获取右侧和左侧重载,c++,operator-overloading,C++,Operator Overloading,这更像是一个,我一直想知道的场景。在下面的代码中,tclass有一个int作为私有成员。您可以看到操作符=重载。如果查看主代码,就会看到bbb,它是tclass对象。一行 bbb=7 我们使用操作符获取tclass对象,通过操作符=我能够传递右手int,从而在tclass bbb中填充my_intvalue 与使用intyyy=5时的预期大致相同,右侧的5被传递到yyy的值中 那么,如何重载tclass以获取我在main()中所拥有的内容,但它被注释掉了,因为我无法理解它 yyy=bbb 其中b

这更像是一个,我一直想知道的场景。在下面的代码中,
tclass
有一个
int
作为私有成员。您可以看到
操作符=
重载。如果查看主代码,就会看到
bbb
,它是
tclass
对象。一行
bbb=7

我们使用操作符获取
tclass
对象,通过
操作符=
我能够传递右手
int
,从而在
tclass bbb中填充
my_intvalue

与使用
intyyy=5
时的预期大致相同,右侧的5被传递到
yyy
的值中

那么,如何重载
tclass
以获取我在
main()
中所拥有的内容,但它被注释掉了,因为我无法理解它

yyy=bbb

其中
bbb
my_intvalue
的值被传递到
yyy
,一个
int

Main code Testing.cpp

// Testing.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "tclass.h"



int _tmain(int argc, _TCHAR* argv[])
{
    tclass bbb;
    int yyy = 5;
    bbb = 7;

    //yyy = bbb;

    return 0;
}
tclass.h

#pragma once

#ifndef TCLASS_H
#define TCLASS_H

class tclass
{
private:
    int my_intvalue;
public:
    tclass()
    {
        my_intvalue = 0;
    }
    ~tclass()
    {
    }
    tclass& operator= (int rhs)//right hand
    {
        this->my_intvalue = rhs;
        return *this;
    }

    private:
};

#endif

不能将对象传递给
int
,除非为类
tclass
定义

class tclass
{
// previous stuff
    operator int() // conversion to int operator
    {
        return my_intvalue;
    }
};
然后你可以像这样使用它

int yyy = bbb; // invokes the bbb.operator int()
正如@Yongwei Wu在下面的评论中提到的,有时转换操作符可能会在代码中引入微妙的“问题”,因为转换将在您最不期望的时候执行。为了避免这种情况,您可以将操作符标记为显式的(C++11或更高版本),例如

然后你必须明确地说你想要一个转换

int yyy = static_cast<int>(bbb); // int yyy = bbb won't compile anymore
就这样说吧

int yyy = bbb.to_int();

最好避免自动转换,以免让您感到意外。我认为一般的建议是您应该实现一个
to_int()
成员,并显式地使用
yyy=bbb.to_int()
。Scott Meyers有一个特定的项目叫做“警惕用户定义的转换函数”。@YongweiWu true,非显式转换构造函数也是如此。然而,我认为让OP了解他们是件好事。如果您希望安全,现在可以(C++11或更高版本)声明转换运算符
explicit
,然后需要
静态转换(bbb)
int to_int() { return my_intvalue;}
int yyy = bbb.to_int();