C++之单例模式

test.h

#include <iostream> #include <string> #include <vector> using namespace std; namespace NS_TEST{ class Animal{ public: std::string Name; int Foot; vector<std::string> FileArray; static int abc; public: Animal(std::string name , int foot){ Name = name; Foot = foot; }; ~Animal(){}; static int getEye(){ return 2; } int getFoot(); string getName(); int *getFootPtr(); static Animal* getObj(); }; }

test.cpp

 

#include "stdafx.h"
#include "test.h"


namespace NS_TEST {
int Foot = 234;
int Animal::getFoot(){
    return Foot;
};

string Animal::getName(){
    return Name;
}

int *Animal::getFootPtr()
{
    return &Foot;
}

Animal *Animal::getObj(){
    /*Animal pig("im pig",4);
    return &pig;*/      //不能这样返回地址变量,因为这个地址变量的作用域只在这个函数里。这样的指针会成为野指针

    Animal *pointer=new Animal("im pig",4);  //而new的就不一样了,是直接分配在堆栈里
    return pointer;
}

int Animal::abc = 234234;

}

 

 

main.cpp

 

 

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "test.h"
#include <iostream>
#include <string>
#include <list>
#include <map>
#include <vector>
using namespace std;

namespace NS_MAIN{

    

int func(){
    return 3;
}
}

void main(){
    
    typedef int a;
    a b,c;
    b=10;
    NS_TEST::Animal bear("im bear",4);
    NS_TEST::Animal* p;
    p = &bear;

    int* result = p->getFootPtr();
    cout << "ptr address: "<< result << ", value: " << *result << endl;

    NS_TEST::Animal *AnimalObj = NS_TEST::Animal::getObj();


    int eye = AnimalObj->getFoot();

    cout<< eye <<endl;

    cout<<p->getName()<<endl;

    



}

 

posted on 2014-11-21 15:11  allen__  阅读(189)  评论(0编辑  收藏  举报

导航