C ++重载运算符=以获得右手和左手重载
C++ Overloading operator= to get right and left hand overload
这更像是一个我一直想知道的场景。在下面的代码中,tclass
有一个 int
作为私有成员。您可以看到 operator=
过载。如果查看主要代码,您会看到 bbb
这是一个 tclass
对象。在一行中
bbb = 7;
我们使用运算符获取一个 tclass
对象并通过 operator=
我能够传递右手 int
,从而填充 my_intvalue
tclass bbb;
如果您有一个 int yyy = 5
,右手 5 将传递给 yyy
的值。
那么,你如何重载 tclass
来获得我在 main()
中的内容,但它被注释掉了,因为我无法弄清楚
yyy = bbb;
其中 bbb
中 my_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
您不能将对象传递给 int
,除非您为 class tclass
、
定义 conversion-to-int operator
class tclass
{
// previous stuff
operator int() // conversion to int operator
{
return my_intvalue;
}
};
那你就可以像这样使用了
int yyy = bbb; // invokes the bbb.operator int()
正如@Yongwei Wu 在下面的评论中提到的,有时转换运算符可能会在您的代码中引入微妙的 "issues",因为转换会在您最意想不到的时候执行。为避免此类情况,您可以将运算符标记为 explicit
(C++11 或更高版本),例如
explicit operator int() { return my_intvalue;}
然后你必须明确表示你想要转换
int yyy = static_cast<int>(bbb); // int yyy = bbb won't compile anymore
或使用不同的 "conversion" 函数
int to_int() { return my_intvalue;}
并称其为
int yyy = bbb.to_int();
这更像是一个我一直想知道的场景。在下面的代码中,tclass
有一个 int
作为私有成员。您可以看到 operator=
过载。如果查看主要代码,您会看到 bbb
这是一个 tclass
对象。在一行中
bbb = 7;
我们使用运算符获取一个 tclass
对象并通过 operator=
我能够传递右手 int
,从而填充 my_intvalue
tclass bbb;
如果您有一个 int yyy = 5
,右手 5 将传递给 yyy
的值。
那么,你如何重载 tclass
来获得我在 main()
中的内容,但它被注释掉了,因为我无法弄清楚
yyy = bbb;
其中 bbb
中 my_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
您不能将对象传递给 int
,除非您为 class tclass
、
class tclass
{
// previous stuff
operator int() // conversion to int operator
{
return my_intvalue;
}
};
那你就可以像这样使用了
int yyy = bbb; // invokes the bbb.operator int()
正如@Yongwei Wu 在下面的评论中提到的,有时转换运算符可能会在您的代码中引入微妙的 "issues",因为转换会在您最意想不到的时候执行。为避免此类情况,您可以将运算符标记为 explicit
(C++11 或更高版本),例如
explicit operator int() { return my_intvalue;}
然后你必须明确表示你想要转换
int yyy = static_cast<int>(bbb); // int yyy = bbb won't compile anymore
或使用不同的 "conversion" 函数
int to_int() { return my_intvalue;}
并称其为
int yyy = bbb.to_int();