操作员重载基本 [英] operator overload basic

查看:57
本文介绍了操作员重载基本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Nybble
{
    int val; // underlying storage 

    public Nybble() { val = 0; }

    public Nybble(int i)
    {
        val = i;
        val = val & 0xF; // retain lower 4 bits 
    }

    // Overload binary + for Nybble + Nybble.  
    public static Nybble operator +(Nybble op1, Nybble op2)
    {
        Nybble result = new Nybble();

        result.val = op1.val + op2.val;

        result.val = result.val & 0xF; // retain lower 4 bits  

        return result;
    }

    // Overload binary + for Nybble + int.  
    public static Nybble operator +(Nybble op1, int op2)
    {
        Nybble result = new Nybble();

        result.val = op1.val + op2;

        result.val = result.val & 0xF; // retain lower 4 bits  

        return result;
    }

    // Overload binary + for int + Nybble.  
    public static Nybble operator +(int op1, Nybble op2)
    {
        Nybble result = new Nybble();

        result.val = op1 + op2.val;

        result.val = result.val & 0xF; // retain lower 4 bits  

        return result;
    }

    // Overload ++. 
    public static Nybble operator ++(Nybble op)
    {
        Nybble result = new Nybble();
        result.val = op.val + 1;

        result.val = result.val & 0xF; // retain lower 4 bits 

        return result;
    }

    // Overload >. 
    public static bool operator >(Nybble op1, Nybble op2)
    {
        if (op1.val > op2.val) return true;
        else return false;
    }

    // Overload <. 
    public static bool operator <(Nybble op1, Nybble op2)
    {
        if (op1.val < op2.val) return true;
        else return false;
    }

    // Convert a Nybble into an int. 
    public static implicit operator int(Nybble op)
    {
        Console.WriteLine("obj to int");
        return op.val;
    }

    // Convert an int into a Nybble. 
    public static implicit operator Nybble(int op)
    {
        Console.WriteLine("int to obj");
        return new Nybble(op);
    }
}

class NybbleDemo
{
    static void Main()
    {
        Nybble a = new Nybble(1);
        Nybble b = new Nybble(10);
        Nybble c = new Nybble();
        int t;

        Console.WriteLine("a: " + (int)a);//(1)
        Console.WriteLine("b: " + (int)b);

        // Use a Nybble in an if statement. 
        if (a < b) Console.WriteLine("a is less than b\n");

        // Add two Nybbles together. 
        c = a + b;
        Console.WriteLine("c after c = a + b: " + (int)c);

        // Add an int to a Nybble. 
        a += 5;
        Console.WriteLine("a after a += 5: " + (int)a);

        Console.WriteLine();

        // Use a Nybble in an int expression. 
        t = a * 2 + 3;
        Console.WriteLine("Result of a * 2 + 3: " + t);

        Console.WriteLine();

        // Illustrate int assignment and overflow. 
        a = 19;
        Console.WriteLine("Result of a = 19: " + (int)a);

        Console.WriteLine();

        // Use a Nybble to control a loop. //(2)                    Console.WriteLine("Control a for loop with a Nybble.");
        for (a = 0; a < 10; a++)
            Console.Write((int)a + " ");
        Console.WriteLine();
    }
}



这些行被标记并带有下划线:
(1)当我已经实现了隐式锥体转换时,为什么需要显式转换它?

(2)在for循环中,a = 0(已初始化),因此应首先调用obj的int,然后应返回新的对象引用,然后将obj打印到int,然后再打印值.但是,此程序的输出有点混乱,因为它将int两次打印到obj,然后将值打印一次,然后将obj打印一次,然后再对循环中的每个a ++将int打印到obj?请解释.




The lines are labelled and underlined:
(1)Why do you need to explicitly cast it when I have already implemented a implicit coneversion?

(2)In the for loop, a = 0(initialised), hence the int to obj should be called first then it should return the new object reference then it should print obj to int then the value. But the output to this program is a little cofusing as it prints int to obj twice and the value and then obj to int once and furher it prints int to obj for every a++ in the loop? please explain.


Thanks in advance!

推荐答案

好吧,我会尽力清楚地解释您的for循环中的代码.

您的前两行输出是在代码进入此部分的for循环时编写的:
Okay, I''ll try to explain the code in your for loop as clearly as I can.

Your first two lines of output was written when the code enter the for loop in this part:
for (a = 0; a < 10; a++) //convert 0 and 10 to Nybble


10转换为Nybble会导致您仅覆盖运算符<从Nybble到Nybble,而不是Nybble到int.
导致代码将这些行写入编译器


10 converted to Nybble cause you only override operator < for Nybble to Nybble, not Nybble to int.
causing the code to write these lines to the compiler

int to obj<br />
int to obj



下一行写在您的循环中



The next lines were written in your loop

Console.Write((int)a + " "); //cast a to int and print the string


我假设您已经知道上面的代码将打印此输出:


I assume you already know that above code will print this output:

obj to int<br />
0 

-0后面有一个空格

所以,为什么代码会打印

--There''s a space after 0

So, why did the code print

obj to int<br />
0 int to obj 


而不是高于期望的输出?

这是因为您正在实现单行循环
因此,在代码打印0 之后,代码将返回此处以检查循环:


instead of above desired output?

This is because you''re implementing a one-line loop
Therefore, after the code print 0 the code will go back to check the loop here:

for (a = 0; a < 10; a++) //execute a++ first, then check if a < 10


执行对a < 10的检查时,代码将在您先前的输出旁边打印int to obj.
导致您的输出高于

现在尝试将循环更改为这一循环:


When the check to a < 10 is performed, the code will print int to obj next to your previous output
resulting in your output above

Now try to change the loop into this one:

for (a = 0; a < 10; a++){
    Console.Write((int)a + " ");
    Console.WriteLine();
}


输出应如下所示:


The output should be like this :

int to obj<br />
int to obj<br />
obj to int<br />
0<br />
int to obj<br />
obj to int<br />
1<br />
int to obj<br />
obj to int<br />
....


在第一种情况下需要进行强制转换的原因是因为您在字符串上使用了+运算符.

当您执行"a:" + a时,编译器将尝试查找从Nybble到字符串的运算符.由于找不到该对象,因此默认情况下将在该对象上调用ToString().添加一个返回字符串的隐式运算符将解决该问题.

第二种情况也按预期工作.首先将a初始化为0.然后验证a<是否为0. 10(这意味着您必须再次调用运算符),然后执行Console.WriteLine((int)a),它将调用转换为int的运算符.

这对您有意义吗?

谢谢,
亚历克斯
The reason why you need a cast in the first case is because you are using the + operator on strings.

When you are doing "a: " + a, the compiler will try to find an operator that goes from a Nybble to a string. Since it cannot find one, it will default to calling ToString() on the object. Adding an implicit operator that returns a string will solve that issue.

The second case also works as expected. You are first initializing the a to 0. Then you are verifying that a < 10 (which means you have to call the operator again) and then you are doing Console.WriteLine((int)a) which will call the operator that converts to int.

Does this make sense to you?

Thanks,
Alex


对于WriteLine,我建议您的课程覆盖ToString().

对于比较a < 10,您尚未定义任何允许将Nybbleint进行比较的运算符.看起来编译器每次进行比较时都会将10转换为Nybble.

因此,您可以通过编写类似以下内容来优化循环:

For WriteLine, I would suggest that your class override ToString().

For the comparison a < 10, you have not define any operator that allows to compare a Nybble with an int. It look like the compiler will convert 10 to a Nybble every time it does the comparision.

Thus you could optimize your loop by writting something like that:

class Nybble
{
    // Existing stuff...

    public override ToString() { return val.ToString(); }
}

Nybble limit = new Mybble(10);
for (a = 0; a < limit; ++a)
{
    Console.Write(a.ToString() + "");
}


这篇关于操作员重载基本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆