Substrac Fraction C++
Jun 2, 2012 at 11:38am UTC
This is my code, and I don't know what does "this" mean in my code.
I just followed the example to do my assignment, and I would like to know how "this" work.
Please help me. Thank you :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
// ProgrammingAssignmentEight.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
// ====================
struct Fraction {
int den;
int num;
// ============
void SetNum( ) {
cout << "Please enter an integer value for num: " ;
cin >> num;
} // Function SetNum
// ====================
// ===============
void SetDen( ){
cout << "Please enter an integer value for den: " ;
cin >> den;
} // Function SetDen
// ====================
// ==============================
void Print( string varName ) {
cout << varName << " = " << num << "/" << den << endl;
} // Function Print
// ===================
// ========================================
void Subtract( Fraction u, Fraction v ) {
int a, b, c, d;
Fraction w;
a = u.num;
b = u.den;
c = v.num;
d = v.den;
w.num = a*d - b*c;
w.den = b*d;
this ->num = w.num;
this ->den = w.den;
} // Substract Function
// =======================
}; // Structure Fraction
// ===============
int main() {
// =======================================
// Declare three Variable of type Fraction
// =======================================
Fraction x;
Fraction y;
Fraction z;
// ===============
x.SetNum();
x.SetDen();
x.Print("x" );
y.SetNum();
y.SetDen();
y.Print("y" );
z.Subtract(x,y);
z.Print("z" );
return 0;
} // Function Main
Jun 2, 2012 at 11:50am UTC
In C++, every class has an implicit pointer to itself. The pointer is named "this". There are practical uses of it. The case above is not a good use of it. You can simply remove the
this ->
Topic archived. No new replies allowed.