c++ class examples
[code language=”cpp”]
#include <iostream>
using namespace std;
//Triangle class definition
class Triangle {
int b, h;
public:
void set_values (int,int); //prototype, definition outside
int area ()
{
return (b*h)/2;
}
};
/**
* operator of scope (::, two colons), tt is used to define a member of a class
* from outside the class definition itself
*/
void Triangle::set_values (int a, int b) {
Triangle::b = a;
Triangle::h = b;
}
int main(int argc, char** argv) {
Triangle tri;
tri.set_values (3,4);
cout << "Area of a triangle with base 3 and height 4: " << tri.area();
return 0;
}
[/code]
Output:
[code language=”cpp”]
Area of a triangle with base 3 and height 4: 6
[/code]
Search within Codexpedia
Search the entire web