重载操作符=获得左、右重载
C++ Overloading operator= to get right and left hand overload
这更像是一个我一直想知道的场景。在下面的代码中,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();
相关文章:
- 重载操作符+:表达式必须是整型或无作用域枚举类型
- 重载操作符
- 如何重载操作符==外模板类使用友元函数
- 重载*操作符,使其在左右两边都工作
- 重载操作符<对于非随机迭代器
- 在c++中重载操作符的时间和原因
- 如何在c++中重载=操作符来通过引用进行复制
- 如何在c++中获取定义为友元的重载操作符的地址
- 使用重载操作符的文件操作表达式没有给出预期的结果
- 重载操作符()
- 重载操作符()并在类内使用
- 类中的重载操作符+
- 定时使用重载操作符
- c++带类的重载操作符
- 用列表容器重载[]操作符
- 重载操作符=
- 任何重载操作符()的静态检测
- 重载操作符以处理类对象
- 在使用另一个类的类中重载操作符==
- 派生类和基类中的重载操作符不同