簡體   English   中英

C ++重載operator =獲得右手和左手過載

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

這更像是一個,我一直想知道情景。 在以下代碼中, tclass將一個int作為私有成員。 你可以看到operator= overload。 如果查看主代碼,可以看到bbb是一個tclass對象。 在一行bbb = 7;

我們使用運算符來獲取tclass對象並通過operator=我能夠傳遞一個右手int ,從而在tclass bbb;填充my_intvalue tclass bbb;

如果你有一個int yyy = 5 ,那么右手5將被傳遞到yyy的值中。

那么,你如何重載tclass來獲取我在main()但是它被注釋掉了,因為我無法弄明白

yyy = bbb;

其中bbbmy_intvalue的值傳遞給yyy ,一個int ;

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

除非為類tclass定義tclass -to-int運算符 ,否則不能將對象傳遞給int

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM