上次的code可以做如下改动:
#include
<
iostream
>
using namespace std;
class sha
{
static int a;
int b;
public :
void set ( int i, int j)
{
// a=i;
b = j;
}
static void seta( int i)
{
a = i;
}
void show();
static void showa();
};
void sha::show()
{
// cout<<"this is static a="<<a<<endl;
std::cout << " this is non-static b= " << b << endl;
}
void sha::showa()
{
// cout<<"this is static a="<<a<<endl;
std::cout << " this is static a= " << a << endl;
}
int sha::a = 1 ;
int main()
{
sha x,y;
x. set ( 1 , 1 );
x.show();
y. set ( 2 , 2 );
y.show();
y.seta( 10 );
x.show();
x.showa();
return 0 ;
}
using namespace std;
class sha
{
static int a;
int b;
public :
void set ( int i, int j)
{
// a=i;
b = j;
}
static void seta( int i)
{
a = i;
}
void show();
static void showa();
};
void sha::show()
{
// cout<<"this is static a="<<a<<endl;
std::cout << " this is non-static b= " << b << endl;
}
void sha::showa()
{
// cout<<"this is static a="<<a<<endl;
std::cout << " this is static a= " << a << endl;
}
int sha::a = 1 ;
int main()
{
sha x,y;
x. set ( 1 , 1 );
x.show();
y. set ( 2 , 2 );
y.show();
y.seta( 10 );
x.show();
x.showa();
return 0 ;
}
输出结果:
this is non-static b=1
this is non-static b=2
this is non-static b=1
this is static a=10
静态成员须用类名直接访问,不能有对象进行访问, 看如下例子:
#include
<
iostream
>
#pragma warning(disable: 4101)
using namespace std;
class C0
{
public :
static void print0() // 这里用static
{
cout << " C0 print0 " << endl;
}
public :
class C1
{
/// //
/// //
public :
void print1()
{
cout << " C0 C1 print1 " << endl;
}
/* ***found**** */
static void print2() // 这里用static
{
cout << " C0 C1 print2 " << endl;
}
};
};
int main()
{
C0::print0();
/// //
C0::C1 obj2;
obj2.print1();
/// /
C0 obj; // 这两行也可以改为:
obj.C1::print2(); // C0::C1::print2();
/* ***found**** */
return 0 ;
}
#pragma warning(disable: 4101)
using namespace std;
class C0
{
public :
static void print0() // 这里用static
{
cout << " C0 print0 " << endl;
}
public :
class C1
{
/// //
/// //
public :
void print1()
{
cout << " C0 C1 print1 " << endl;
}
/* ***found**** */
static void print2() // 这里用static
{
cout << " C0 C1 print2 " << endl;
}
};
};
int main()
{
C0::print0();
/// //
C0::C1 obj2;
obj2.print1();
/// /
C0 obj; // 这两行也可以改为:
obj.C1::print2(); // C0::C1::print2();
/* ***found**** */
return 0 ;
}
输出结果:
C0 print0
C0 C1 print1
C0 C1 print2
C0 C1 print1
C0 C1 print2