C ++重载operator =获得右手和左手过载

时间:2015-05-23 01:52:51

标签: c++ operator-overloading

这更像是一个,我一直想知道情景。在以下代码中,tclass有一个int作为私有成员。您可以看到operator=重载。如果查看主代码,您会看到bbbtclass对象。在一条线上 bbb = 7;

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

如果你有一个int yyy = 5,那么就像你期望的那样,右手5被传递到yyy的值。

那么,你如何重载tclass以获得main()中的内容,但它被注释掉了,因为我无法弄清楚

yyy = bbb;

my_intvaluebbb的值传递给yyyint;

主要代码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

1 个答案:

答案 0 :(得分:3)

除非您为班级 <a href="#"><div class="button_cadre_work"><div id="work_btn">WORKS</div> <div id="blank_work"></div> </div></a> 定义conversion-to-int operator,否则无法将对象传递给int

tclass

然后你可以像

一样使用它
class tclass
{
// previous stuff
    operator int() // conversion to int operator
    {
        return my_intvalue;
    }
};

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

explicit

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

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;}