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