zoukankan      html  css  js  c++  java
  • [转]类的自动类型转换和转换操作符

    1.当构造函数只接受一个参数时,则该类可以与该参数类型相同的值转换。

    看下面这个简单的例子:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    // Woo.h file
    #ifndef WOO_H
    #define WOO_H
     
    class Woo{
    private:
    	double mm;
    public:
    	/*explicit*/ Woo(double a);
    	Woo() {mm=0;};
    	void show();
     
    	//operator double() const;
    };
     
    #endif
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    // Woo.cpp file
    #include "stone.h"
    #include <iostream>
    using namespace std;
     
    Woo::Woo(double a)
    {
    	mm = a;
    }
     
    void Woo::show()
    {
    	cout << "show function: " << mm << endl;
    }
     
    /*
    Woo::operator double() const
    {
    	return double(mm);
    }
    */
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
    // main.cpp file
    #include "stone.h"
    #include <iostream>
    using namespace std;
     
    int main()
    {
    	Woo a;
    	a = 13.3;
    	a.show();
     
    	/*
    	Woo a(13.3);
    	double b = a;
    	cout << b << endl;
    	*/
    }

    运行结果:

    zhuanhuan

    其实,此处重点还是因为在赋值时,创建了一个该类的临时变量,然后将临时变量赋值给该类变量。

    如果想要关闭这个特性,可以使用explicit关键字,只需要在类声明中的构造函数前加上explicit即可,如:

    1
    
    explicit Woo(double a);

    此时我在VS2008下显示报错:

    error C2679: 二进制“=”: 没有找到接受“double”类型的右操作数的运算符(或没有可接受的转换)

    2.C++类型转换操作符

    在上面,符合条件时,可以将double赋值给一个类类型,那反过来行吗?

    可以,不过此时要使用C++的转换操作符函数。

    转换函数是用户定义的强制类型转换,可以像使用强制类型转换一样使用它们。

    转换函数的使用方法:

    operator typeName();

    typeName是要转换为的类型。

    注意以下几点:

    ①.转换函数必须是类方法。

    ②.转换函数不能指定返回类型。

    ③.转换函数不能有参数。

    我们还是使用上面的例子:
    直接把注视掉的地方,把注视符号去掉即可。

    运行结果:

    zhuanhuan2

    转自wutianqi博客:http://www.wutianqi.com/?p=2730

  • 相关阅读:
    3:Exchange2016图形化安装和无人值守安装
    hdu 3980 Paint Chain (sg)
    hdu 1850 Being a Good Boy in Spring Festival (Nim)
    zoj 2971 Give Me the Number
    hdu 1847 Good Luck in CET4 Everybody! (sg)
    hdu 1754 I hate it (线段树)
    poj 1704 Georgia ans Bob (StaircaseNim)
    hdu 1907 John (Nim变形)
    hdu 1536 SNim (sg)
    hdu 1166 敌兵布阵 (线段树)
  • 原文地址:https://www.cnblogs.com/chenbin7/p/2198694.html
Copyright © 2011-2022 走看看