zoukankan      html  css  js  c++  java
  • static 成员函数

    和静态数据成员一样,静态成员函数是所有对象共享的,不是单独属于某一个对象,由于静态成员函数没有传递this指针,故static member function 只能访问static成员,不能访问非static 成员。但是非static却可以访问static 成员。

     1 #include<iostream>
     2 using namespace std;
     3 class X{
     4     int i;
     5     static int j;
     6 public:
     7     X(int ii=0) :i(ii){
     8         j = i;//non-static member function can access static member function or data
     9     }
    10     int val()const{ return i; }
    11     static int incr(){
    12         //i++; Error:static member function can not access non-static member data
    13         return ++j;
    14     }
    15     static int f(){
    16         //!val()    Error:static member function can not access non-static member function
    17         return incr();
    18     }
    19 
    20 };
    21 int X::j = 0;
    22 int main(){
    23     X x;
    24     X* xp = &x;
    25     x.f();
    26     xp->f();
    27     X::f();
    28     system("pause");
    29     return 0;
    30 
    31 }

    对象在访问静态成员时,可以通过点运算符和箭头运算符。这样就把静态成员函数与某一个对象相连接了,也可以直接用  className::static member fucntion name 的方式访问。

    有时可以把构造函数设置成私有的,如下面的例子

     1 class Egg{
     2     static Egg e;
     3     int i;
     4     Egg(int ii) :i(ii){}
     5     Egg(const Egg&);//prevent copy-construction
     6 public:
     7     static Egg* instance(){ return &e; }
     8     int val()const{ return i; }
     9 };
    10 
    11 Egg Egg::e(47);
    12 int main(){
    13     //! Egg x(0); Error can't create an Egg
    14     cout << Egg::instance()->val() << endl;
    15     system("pause");
    16     return 0;
    17 
    18 }

    为了不让类可以拷贝创建对象,增加了一个私有的拷贝构造函数

    Egg(const Egg&);//prevent copy-construction
    这样类就不可以如下的创建对象了
    Egg e=*Egg::instance();
  • 相关阅读:
    ASP.NET 3.5 的 ListView 控件与 CSS Friendly
    从 Adobe SHARE 说到 Silverlight 的 XPS 支持
    编写 iPhone Friendly 的 Web 应用程序 (Part 5 交互入门)
    初为项目经理
    管理的最高境界不是完美
    url传递中文的解决方案总结
    我想跟什么样的人合作
    异步Socket通信总结
    让机器自动支持中文文件名
    Socket基本编程
  • 原文地址:https://www.cnblogs.com/cplinux/p/5612034.html
Copyright © 2011-2022 走看看