编程中国 | 业界新闻 | 技术文章 | 视频教程 | 下载频道 | 程序源码 | 个人空间 | 编程论坛  
全能 ASP / PHP / ASP.NET 主机,支持月付专业 MSSQL 数据库空间,支持月付专业 MySQL 数据库空间,支持月付学习型 ASP/PHP/ASP.NET 主机 30元/年
 21 123
发新话题
打印

static成员能否被继承?

static成员能否被继承?

如题!

TOP

汇编.....

TOP

回复 1# newyj 的帖子

如果再加上private,肯定不行...

static变量和方法只能用类名来访问。
Java Lover QQ Group : 64666806

TOP

试验下就知道了
Fight  to win  or  die...

TOP

能能能能

TOP

For example:
引用:
#include <iostream>
using namespace std;

class Base
{
   public:
   static int a;
   static void Fun( )
   {
       cout<<"静态成员函数可以被继承!"<<endl;
   }
};
int Base::a=1000;

class Derived:public Base
{

};
int main(void)
{
  cout <<"静态数据成员可以被继承!  "<<Derived::a<<endl;
  Derived::Fun( );
  system("pause");
  return 0;
}
i like linux...

TOP

谢谢各位的回答!

TOP

static继承下来的,从基类到派生类只保存一份数据,,是共享的,通常用来基类和派生类之间的联系

TOP

请问3# Ethip

引用:
Ethip 在 2008-6-6 21:06 的发言:

如果再加上private,肯定不行...

static变量和方法只能用类名来访问。
staitc变量和方法为什么只能用类名来访问?虽然这种变量和方法是独立存在的,即没有和具体实例进行绑定,但也是允许通过实例名来访问的。

TOP

我发现个现象。在main函数外面初始化Base的私有成员变量a是可以的。比如:



#include <iostream>
using namespace std;

class Base
{
private:
    static int a;
public:

    static void Fun( )
    {
        cout<<"静态成员函数可以被继承!"<<endl;
        a++;
        cout<<"第"<<a<<"次被调用"<<endl;
    }
};


class Derived:public Base
{
    
};

int Base::a=0; //比如这个样子

int main(int argc, char* argv[])
{


    int b=1;
    
    while (b)
    {
        
        Derived::Fun( );
        cout <<"是否继续?退出输入0  "<<endl;
        cin>>b;
    }
    
    
    return 0;

}

但是在main函数里面初始化基类的静态成员函数却不可以。比如:
#include "stdafx.h"

#include <iostream>
using namespace std;

class CbaseClass
{
private:
    static int a;
public:

    static void Fun( )
    {
        cout<<"静态成员函数可以被继承!"<<endl;
        a++;
        cout<<"第"<<a<<"次被调用"<<endl;
    }
};


class CDerived:public CbaseClass
{
    
};


int main(int argc, char* argv[])
{

         CbaseClass::a=0; //在主函数这里初始化,编译是没有问题的,但却在连接时出错。

    int b=1;
    
    while (b)
    {
        
        CDerived::Fun( );
        cout <<"是否继续?退出输入0  "<<endl;
        cin>>b;
    }
    
    
    return 0;

}

这是为什么呢?

我用的编译器是VC6 with sp6
错误信息是:
error LNK2001: unresolved external symbol "public: static int CbaseClass::a" (?a@CbaseClass@@2HA)
[ 本帖最后由 VanHorn 于 2008-6-9 21:11 编辑 ]

[ 本帖最后由 VanHorn 于 2008-6-9 21:14 编辑 ]
我用VC++6我怕谁?

TOP

 21 123
发新话题