CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Guest

    Question on constructors

    Question on constructors.
    I have an assignemnt that asks for 4 constructors and i have created the first and second but "the third constructor will have two arguments - a numerical measure of distance and units of distance (feet, yards, miles). Using this third constructor, one could instantiate a Distance object by specifying a number as one argument and a unit of measure as a second argument. You must use a code to indicate the unit of measure. Use "f" for feet, "y" for yards, and "m" for miles. The uppercase version of these codes must be valid also."

    I am not sure how to make this constructor work.
    the following is what I have:

    public class Distance
    {

    private int feet;
    private int yards;
    private int miles;

    // first constructor
    public Distance()
    {
    feet = yards = miles = 0;
    }

    // second constructor
    public Distance(int f)
    {
    feet = f;
    }
    // third constructor
    public Distance(int y, char y)
    {
    }


    public int getFeet()
    {
    return feet;
    }

    public int getYards()
    {
    return yards;
    }

    public int getMiles()
    {
    return miles;
    }

    public void setFeet(int f)
    {
    feet = f;
    }

    public void setYards(int y)
    {
    yards = y;
    }

    public void setMiles(int m)
    {
    miles = m;
    }
    }



  2. #2
    Guest

    Re: Question on constructors

    If I understand your queston correctly, you want to figure out how to assign the number to the correct variable?
    You could do it like this:


    //...
    // second constructor
    public Distance(int f)
    {
    feet = f;
    }
    //
    // third constructor
    //
    public Distance(int y, char units) // Both variables cannot be named y, so I named the second units.
    {
    switch(units)
    {
    case 'f':
    case 'F':
    feet = y;
    break;
    case 'm':
    case 'M':
    miles = y;
    break;
    case 'y':
    case 'Y':
    yards = y;
    break;
    default:
    feet = yards = miles = 0;
    }
    }





Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured