重载操作符=获得左、右重载

C++ Overloading operator= to get right and left hand overload

本文关键字:重载 操作符      更新时间:2023-10-16

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

我们使用运算符获取tclass对象,并通过operator=传递右手int,从而填充tclass bbb;

中的my_intvalue

int yyy = 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在下面的评论中提到的,有时转换操作符可能会在你的代码中引入微妙的"问题",因为转换将在你最不期望的时候执行。为了避免这种情况,您可以将操作符标记为explicit (c++ 11或更高版本),例如

explicit operator int() { return my_intvalue;}

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

int yyy = static_cast<int>(bbb); // int yyy = bbb won't compile anymore

或者使用不同的"转换"函数

int to_int() { return my_intvalue;}

并将其命名为

int yyy = bbb.to_int();