开发者

Transitioning from C# to C++, good references?

I've just completed my second OOP class, and both my first and second classes were taught in C#, but for the rest of my programming classes, we will be working in C++. Specifically, we will be using the visual C++ compliler. The problem is, we are required to learn the basics of C++ ourself, with no transition from our professor. So, I was wondering if any of you know of some good resources I could go to to learn about C++, coming from a c# background?

I ask this because I've noticed many diffferences between C# and C++, such as declaring your main method int, and returning a 0, and that your main method is not always contained in a class. Also, I've noticed that all of your classes have to be written before your main method, I heard that this is because VC++ complies from the top down?

Anyway, do you know of some good references?

Thanks! (Also, is there somewhere out there where I can compare simple programs I've written in C#, to see what they would look like in C++, such as the one I wrote that is below)?

using System;
using System.IO;
using System.Text; // for stringbuilder

class Driver
{
const int ARRAY_SIZE = 10;

static void Main()
{
    PrintStudentHeader(); // displays my student information header

    Console.WriteLine("FluffShuffle Electronics Payroll Calculator\n");
    Console.WriteLine("Please enter the path to the file, either relative to your current location, or the whole file path\n");

    int i = 0;

    Console.Write("Please enter the path to the file: ");
    string filePath = Console.ReadLine();

    StreamReader employeeDataReader = new StreamReader(filePath);

    Employee[] employeeInfo = new Employee[ARRAY_SIZE];

    Employee worker;

    while ((worker = Employee.ReadFromFile(employeeDataReader)) != null)
    {
        employeeInfo[i] = worker;
        i++;
    }

    for (int j = 0; j < i; j++)
    {
        employeeInfo[j].Print(j);
    }

    Console.ReadLine();

}//End Main()


class Employee
{
const int TIME_AND_A_HALF_MARKER = 40;
const double FEDERAL_INCOME_TAX_PERCENTAGE = .20;
const double STATE_INCOME_TAX_PERCENTAGE = .075;
const double TIME_AND_A_HALF_PREMIUM = 0.5;

private int employeeNumber;
private string employeeName;
private string employeeStreetAddress;
private double employeeHourlyWage;
private int employeeHoursWorked;
private double federalTaxDeduction;
private double stateTaxDeduction;
private double grossPay;
private double netPay;

// -------------- Constructors ----------------

public Employee() : this(0, "", "", 0.0, 0) { }

public Employee(int a, string b, string c, double d, int e)
{
    employeeNumber = a;
    employeeName = b;
    employeeStreetAddress = c;
    employeeHourlyWage = d;
    employeeHoursWorked = e;
    grossPay = employeeHourlyWage * employeeHoursWorked;

    if (employeeHoursWorked > TIME_AND_A_HALF_MARKER)
        grossPay += (((employeeHoursWorked - TIME_AND_A_HALF_MARKER) * employeeHourlyWage) * TIME_AND_A_HALF_PREMIUM);

    stateTaxDeduction = grossPay * STATE_INCOME_TAX_PERCENTAGE;
    federalTaxDeduction = grossPay * FEDERAL_INCOME_TAX_PERCENTAGE;
}

// --------------- Setters -----------------

/// <summary>
/// The SetEmployeeNumber method
/// sets the employee number to the given integer param
/// </summary>
/// <param name="n">an integer</param>
public void SetEmployeeNumber(int n)
{
    employeeNumber = n;
}

/// <summary>
/// The SetEmployeeName method
/// sets the employee name to the given string param
/// </summary>
/// <param name="s">a string</param>
public void SetEmployeeName(string s)
{
    employeeName = s;
}

/// <summary>
/// The SetEmployeeStreetAddress method
/// sets the employee street address to the given param string
/// </summary>
/// <param name="s">a string</param>
public void SetEmployeeStreetAddress(string s)
{
    employeeStreetAddress = s;
}

/// <summary>
/// The SetEmployeeHourlyWage method
/// sets the employee hourly wage to the given double param
/// </summary>
/// <param name="d">a double value</param>
public void SetEmployeeHourlyWage(double d)
{
    employeeHourlyWage = d;
}

/// <summary>
/// The SetEmployeeHoursWorked method
/// sets the employee hours worked to a given int param
/// </summary>
/// <param name="n">an integer</param>
public void SetEmployeeHoursWorked(int n)
{
    employeeHoursWorked = n;
}

// -------------- Getters --------------

/// <summary>
/// The GetEmployeeNumber method
/// gets the employee number of the currnt employee object
/// </summary>
/// <returns>the int value, employeeNumber</returns>
public int GetEmployeeNumber()
{
    return employeeNumber;
}

/// <summary>
/// The GetEmployeeName method
/// gets the name of the current employee object
/// </summary>
/// <returns>the string, employeeName</returns>
public string GetEmployeeName()
{
    return employeeName;
}

/// <summary>
/// The GetEmployeeStreetAddress method
/// gets the street address of the current employee object
/// </summary>
/// <returns>employeeStreetAddress, a string</returns>
public string GetEmployeeStreetAddress()
{
    return employeeStreetAddress;
}

/// <summary>
/// The GetEmployeeHourlyWage method
/// gets the value of the hourly wage for the current employee object
/// </summary>
/// <returns>employeeHourlyWage, a double</returns>
public double GetEmployeeHourlyWage()
{
    return employeeHourlyWage;
}

/// <summary>
/// The GetEmployeeHoursWorked method
/// gets the hours worked for the week of the current employee object
/// </summary>
/// <returns>employeeHoursWorked, as an int</returns>
public int GetEmployeeHoursWorked()
{
    return employeeHoursWorked;
}

// End --- Getter/Setter methods

/// <summary>
/// The CalcSalary method
/// calculates the net pay of the current employee object
/// </summary>
/// <returns>netPay, a double</returns>
private double CalcSalary()
{
    netPay = grossPay - stateTaxDeduction - federalTaxDeduction;

    return netPay;
}

/// <summary>
/// The ReadFromFile method
/// reads in the data from a file using a given a streamreader object
/// </summary>
/// <param name="r">a streamreader object</param>
/// <returns>an Employee object</returns>
public static Employee ReadFromFile(StreamReader r)
{
    string line = r.ReadLine();

    if (line == null)
        return null;

    int empNumber = int.Parse(line);
    string empName = r.ReadLine();
    string empAddress = r.ReadLine();
    string[] splitWageHour = r.ReadLine().Split();
    double empWage = double.Parse(splitWageHour[0]);
    int empH开发者_高级运维ours = int.Parse(splitWageHour[1]);

    return new Employee(empNumber, empName, empAddress, empWage, empHours);
}

/// <summary>
/// The Print method
/// prints out all of the information for the current employee object, uses string formatting
/// </summary>
/// <param name="checkNum">The number of the FluffShuffle check</param>
public void Print(int checkNum)
{
    string formatStr = "| {0,-45}|";

    Console.WriteLine("\n\n+----------------------------------------------+");
    Console.WriteLine(formatStr, "FluffShuffle Electronics");
    Console.WriteLine(formatStr, string.Format("Check Number: 231{0}", checkNum));
    Console.WriteLine(formatStr, string.Format("Pay To The Order Of:  {0}", employeeName));
    Console.WriteLine(formatStr, employeeStreetAddress);
    Console.WriteLine(formatStr, string.Format("In The Amount of {0:c2}", CalcSalary()));
    Console.WriteLine("+----------------------------------------------+");
    Console.Write(this.ToString());
    Console.WriteLine("+----------------------------------------------+");
}

/// <summary>
/// The ToString method
/// is an override of the ToString method, it builds a string
/// using string formatting, and returns the built string. It particularly builds a string containing
/// all of the info for the pay stub of a sample employee check
/// </summary>
/// <returns>A string</returns>
public override string ToString()
{
    StringBuilder printer = new StringBuilder();

    string formatStr = "| {0,-45}|\n";

    printer.AppendFormat(formatStr,string.Format("Employee Number:  {0}", employeeNumber));
    printer.AppendFormat(formatStr,string.Format("Address:  {0}", employeeStreetAddress));
    printer.AppendFormat(formatStr,string.Format("Hours Worked:  {0}", employeeHoursWorked));
    printer.AppendFormat(formatStr,string.Format("Gross Pay:  {0:c2}", grossPay));
    printer.AppendFormat(formatStr,string.Format("Federal Tax Deduction:  {0:c2}", federalTaxDeduction));
    printer.AppendFormat(formatStr,string.Format("State Tax Deduction:  {0:c2}", stateTaxDeduction));
    printer.AppendFormat(formatStr,string.Format("Net Pay:    {0:c2}", CalcSalary()));

    return printer.ToString();

}
}


C++ and C# are different languages, with different semantics and rules. There is no hard and fast way to switch from one to the other. You will have to learn C++.

For that, some of the resources to learn C++ questions may give you interesting suggestions. Search also for C++ books - see the definitive C++ book guide and list, for example.

In any case, you will need a good amount of time to learn C++. If your teacher expects you to just know C++ out of the blue, your school has a serious problem.


My advice is this:

Don't think of C++ in terms of C#. Start from scratch, and try to learn C++ from a good, solid C++ textbook.

Trying to map C++ into a C# way of thinking will not make you a good C++ developer - it's really very different. It's very hard to port from C# to C++ (not C++/CLI, but strait C++), because so much of C# is really the .NET framework, which will not be available when working in C++.

Also, there are very, very many things that are done differently in C++ than how you'd do it in C#. As much as C# generics look like C++ templates, they are very different, and that change really becomes pervasive when working in C++.

Your experience will make many things easier, but it's really better to think of it as what it is - a completely different language.


There isn't really a comparison "place" out there that I'm aware of for checking your code against a C++ implementation of it. What I'd recommend instead is that you find a local expert in OO development and have him or her do a thorough code review of your example code. After that, he or she could probably go over a port to C++ with you, and you'll see the languages aren't terribly different. (The libraries are where you'll find the meaningful differences, not the languages; but that may not be a relevant distinction to you at this point.)

A code review is different than asking your prof or TA to grade your work. The prof likely won't have time to do a full review with you (although he or she may be able to go over a few points in their office.) A good code reviewer will walk you through the code line by line, providing feedback and questions such as "why do you think I would or wouldn't do this?", or "have you considered what will happen if your requirements change to X?", or "what happens to this code if someone else wants to reuse Y?" As you go through the review, they'll be helping reinforce good OO principles. You'll learn a lot of new stuff from someone who's done a lot of these. (Finding a good person may be the difficult task -- get a referral if possible, or ask for someone who is familiar with refactoring. Maybe beg a TA or a grad student to do one.) With your code above, I'd expect it would take an hour or two.

You could also consider asking the StackOverflow denizens to do a code review with you via email or right here in the comments/answers. I'm sure you'd get colorful answers, and the discussion would likely be educational.

It's also valuable to do a code review of an experienced person's code -- asking questions about "why did you do this?" can lead to insight; and it's always great fun when the novice finds a bug in the guru's code.

After you've gone through a review with an expert to see what they're like (even just one or two reviews) consider doing code reviews with your classroom peers, where you each review the other's code. Even an inexperienced set of eyes may ask a question that triggers some deeper understanding.

I realize you have C++ classwork to consider, but you also need more practice with the fundamentals of OO design. Once you have more practical experience, you'll discover that all the C-based languages are pretty much just syntactical variations of a common set of ideas -- although some language features will make your job easier, some will make it harder.


Many colleges and universities teach C#/Java either before or even instead of C++. They do this because there is a belief that you will learn object oriented development more correctly in a language that doesn't allow you to use the non-OO approaches that are still possible in C++.

You should just ask your professor if that is the case.

If it is, you should find that he/she will introduce C++ specifics gently and only where necessary. The aim is that you will be able to apply many of the good practices you learned in C# to your C++ code. You will also more clearly see where C++ allows you to break some OO rules and even more importantly where this can even be useful.

Alternatively, if you find that your professor leaps straight into C++ pointers and memory management without some guidance then (as someone else said) the course does not look very well planned. In this case you may need to look into getting a copy of the C++ Programming Language by Stroustrup.


A book for your specific situation: Pro Visual C++ 2005 for C# Developers

Transitioning from C# to C++, good references?

(Also MSDN notes some differences between them.)


One main thing to always keep in mind is that in C# when you pass an object, you are actually passing a reference to that object.

C#: void EnrollStudent( Student s ) s is a reference (location in memory) to the actual object.

C++: void EnrollStudent( Student s ) s is the actual object. As big as the object is, that's how much space you'll be taking up in the stack.

The C++ equivalent for the C# method is void EnrollStudent( Student* s )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜