c ++运算符重载

Jos*_*son 2 c++

//#include <string>
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;

template<class T, class X> class Obj{
T my_t;
X my_x;
public:
    Obj(T t, X x):my_t(t),my_x(x){}
     operator T() const {return my_t;}
};
int main()
{
    int iT;
    Obj<int, float> O(15,10.375);

    iT = O;
    cout << iT << endl;
    return O;
}
Run Code Online (Sandbox Code Playgroud)

关于这一行:operator T() const {return my_t;} 这个运算符是否过载?但我不太明白哪个运营商超载了?谁能为我解释一下?谢谢!

Tyl*_*nry 5

是的,这是运营商重载.已经过载的运算符是要键入的转换运算符T.这是当您要求编译器将其转换Obj<T,X>为a 时调用的运算符T.

  • `const`意味着与任何其他函数相同,它是编译器的一个信号,在函数调用中不应该修改对象的成员数据.这是真的,因为返回了`my_t`的副本. (2认同)