Click here to Skip to main content
15,905,508 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I want to overload operator * (mutiple), this is my code:
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace WindowsFormsApplication1
{
    public class Matrix
    {
        // Properties
        public int nRow;
        public int nCol;
        public double[,] PhTu;
        // Constructor
        public Matrix(int Ro, int Co)
        {
            this.nRow = Ro;
            this.nCol = Co;
            this.PhTu = new double[Ro, Co];
        }

        public static Matrix operator *(Matrix A)
        {
            if (A.nRow == B.nRow && A.nCol == B.nCol)
              {
                  Matrix C = new Matrix(A.nRow, A.nCol);
                  int i, j;
                  for (i = 0; i < A.nRow; i++)
                      for (j = 0; j < A.nCol; j++)
                          C.PhTu[i, j] = A.PhTu[i, j] + B.PhTu[i, j];

                  return C;
              }
              else
              {
                  MessageBox.Show("Two matrixes are not the same size!");
                  return null;
              }
        }
    }
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Matrix A = new Matrix(2, 1);
            A.PhTu[0, 0] = 1;
            A.PhTu[1, 0] = 3;

            Matrix B = new Matrix(1, 2);
            B.PhTu[0, 0] = -1;
            B.PhTu[0, 1] = 3;

            Matrix C;
            C = A * B;
            for (int i = 0; i < C.nRow; i++)
                for (int j = 0; j < C.nCol; j++)
                {
                    MessageBox.Show(C.PhTu[i, j].ToString());
                }
        }

    }
}


But I cant overload (that code is not working). How to do this? Thanks.
Posted

1 solution

Static operators have to include both sides of the operator, your definition should be:

C#
public static Matrix operator *(Matrix A, Matrix B)
{
//...
}


Otherwise, where did you expect B to come from in a static method?
 
Share this answer
 
Comments
Andrewpeter 13-Dec-13 11:04am    
Oh, I'm absent-minded! Thanks. It's done. +5 to you!
Sergey Alexandrovich Kryukov 13-Dec-13 18:08pm    
Good catch, a 5.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900