• C++类的运算符重载和转换函数结合的问题


        举例,类成员函数重载运算符operator+,参数也为该类的引用。同时定义一个类到int的转换函数,那么在主函数中运行对象相加就有两种可能。1. 对象在隐式转换后变成int类型再进行int类型的相加得到一个int类型的结果;2. 对象运用重载的+运算符得到一个对象结果 ,该对象自动隐式转换成int类型赋给放结果的变量,经过Visual studio2019 C++14测试后实际运行第一种方法。

    #include"iostream"
    
    using namespace std;
    
    class a
    {
    private:   int b=10;
    	     int c = 20;
    public:
    	a& operator +(a&);
    	operator int();
    };
    
    int main()
    {
    	a test1;
    	a test2;
    	int b = 0;
    	b = test1 + test2;
    	std::cout << b;
    }
    
    a& a::operator +(a& e)
    {
    	this->b = this->b + e.c;
    	
    	return *this;
    }
    a::operator int()
    {
    	return b;
    }
    

      

  • 相关阅读:
    Hello World基于.net framework中CLR的执行
    MVN常用命令
    Git常用命令
    Markdown常用语法
    计算机专用英语词汇
    Windows DiskPart
    字符集过滤器
    SSHkey
    书名
    redis
  • 原文地址:https://www.cnblogs.com/XieJunWei666/p/14084350.html
Copyright © 2020-2023  润新知