NaN Quantitavity – Quant Trading, Statistical Learning, Coding and Brainstorming

2012-06-14, 2:06 PM, Thursday

Static members and functions

Filed under: C++ — weekendsunny @ 2:06 PM
// A static member is shared by all objects of the class.
// All static data is initialized to zero when the first object is created, if no other initialization is present.
// We can't put it in the class definition but it can be initialized outside the class
// http://tohtml.com/cpp/

#include <iostream>
using namespace std;

class MyClass
{
public:
      MyClass(){std::cout << "default constructor" << ++count <<endl;}
      static int count;
};

int MyClass::count = 0;

int main(int argc, char** argv)
{
     MyClass* myObjArray = new MyClass[5];
     cout<<MyClass::count<<endl;
}

// A static member function can be called even if no objects of the class exist,
// and the static functions are accessed using only the class name and the scope resolution operator ::.

2012-06-06, 6:33 PM, Wednesday

ASCII Cstring/CharArray to float

Filed under: C++ — weekendsunny @ 6:33 PM
#include <iostream>
using namespace std;

double atofA(char s[]) 
{
    int sign = 1, i = 0, left = 0, power = 10;
    double right = 0.0;

    // Determine the sign:
    if (s[0]=='-')
    {
        sign = -1;
        i++;
    }

    // Calculate the integer part - left:
    while(s[i] && s[i]!='.')
    {
        left = left*10 + (s[i]-'0');
        i++;
    }

    // Calculate the float part - right:
    if (s[i]=='.')
    {
        i++;
        while(s[i])
        {
            right = right + (double)(s[i]-'0')/(power);
            power*=10;
            i++;
        }
    }

    return sign*(left+right);
}

int main()
{
    double d = atofA("-314.1592");
    // double d = atofA("-.1592");
    cout.precision(7);
    cout  << d << endl;
    return 0;
}

// Syntax highlighted at: http://tohtml.com/cpp/

Blog at WordPress.com.

Design a site like this with WordPress.com
Get started