首页 > 解决方案 > 重载运算符时如何放置 6 个值?但是值也可以在之后添加?

问题描述

好的,我知道这看起来很复杂。从代码开始,必须取 2 个字符串 2 个 int 数字并根据输入将它们粉碎在一起,然后输出结果,如下所示:

输入:戴夫 8 杰西卡 7

输出:戴夫和杰西卡 15

我用不同的方法尝试了很多次,但似乎都没有用:(

我尝试将 name1 或 name2 之类的字符串放入 DancerPoints 类,但我找不到与输入连接的方法,我的意思是它存在但无法获得输入。

我也尝试直接将值放入参数中,但它说运算符只能取 2 个值,但我需要 6 个!4 代表舞者,2 代表管理。

此时它只获取 firstdancer 的字符串和 int 并使用它,但我不知道如何添加 seconddancer 的值。

我正在为此工作 3 个晚上,我不知道还能做什么?:(

using System;
using System.Collections.Generic;

namespace Code_Coach_Challenge
{
    class Program
    {
        // I tried putting values here with public but why that not workked I dont know :(

        static void Main(string[] args)
        {
            string name1 = Console.ReadLine();
            int points1 = Convert.ToInt32(Console.ReadLine());
            string name2 = Console.ReadLine();
            int points2 = Convert.ToInt32(Console.ReadLine());

            DancerPoints dancer1 = new DancerPoints(name1, points1);
            DancerPoints dancer2 = new DancerPoints(name2, points2);

            DancerPoints total = dancer1 + dancer2;
            Console.WriteLine(total.name);
            Console.WriteLine(total.points);
        }
    }

    class DancerPoints
    {
        public string name;
        public int points;
                            // I tried putting values here no luck.error CS7036
        public DancerPoints(string name, int points)
        {
            this.name = name;
            this.points = points;
                                  // I tried putting values here no luck.error CS7036
        }

        //overload the + operator
        public static DancerPoints operator+ (DancerPoints n, DancerPoints p)
        {
                                     // I tried putting values here no luck.error CS7036
            string name = n.name + " & " + n.name;
            int points = p.points + p.points;
           
            DancerPoints res = new DancerPoints(name, points);

            return res;
            
  
        }
    }
}

标签: c#operator-overloading

解决方案


如果您希望程序做的只是

  1. 询问姓名1
  2. 求积分1
  3. 询问姓名2
  4. 求积分2
  5. 打印{Name1} & {Name2} {Points1 + Points2}
string name1 = Console.ReadLine();
int points1 = Convert.ToInt32(Console.ReadLine());
string name2 = Console.ReadLine();
int points2 = Convert.ToInt32(Console.ReadLine());

string output = $"{name1} & {name2} {points1 + points2}"
Console.WriteLine(output);

只是简单的字符串连接。不需要任何花哨的类或运算符重载。


现在,如果你想扩展你的代码来一次做两个以上的人,那么

class Dancer
{
    public string Name {get;set;}
    public int Score {get;set;}
}

var dancers = new List<Dancer>
{
    new Dancer { Name = "David", Score = 8 },
    new Dancer { Name = "Jessica", Score = 7 },
    new Dancer { Name = "Sally", Score = 6 },
}

var allNames = string.Join(" & ", dancers.Select(x => x.Name));
var totalScore = dancers.Sum(x => x.Score);
var output = $"{allNames} {totalScore}"

通过这个例子,你会得到

大卫 & 杰西卡 & 莎莉 21

同样,不需要运算符重载。将舞者一起“添加”到一个新的“舞者”对象中并没有真正的意义。


推荐阅读