实例:
#include <iostream>
using namespace std;
class parent
{
public:
void print(void)
{
cout << "parent a=:"<<a<< endl;
}
public:
static int a;
private:
int b;
protected:
int d;
};
int parent::a = 100;
class child3 : public parent
{
public:
void print(int _a)
{
a = _a;
cout << "hello a!"<<a<< endl;
}
private:
int c;
protected:
};
int main()
{
child3 oop;
oop.print(12);
system("pause");
return 0;
}
注意,在parent类中申明的变量a为static int 类型的,但并未实际分配内存,只是告诉编译器,a可以被该类及其其子类使用,int parent:::a=100才是实际分配内存,如果没有int parent:::a=100这句话,同时在基类和子类中都未使用a,则在主函数中调用基类或者派生类的成员函数都不会报错,例如:
#include <iostream>
using namespace std;
class parent
{
public:
#if 0
void print(void)
{
cout << "parent a=:"<<a<< endl;
}
#endif
public:
static int a;
private:
int b;
protected:
int d;
};
//int parent::a = 100;
class child3 : public parent
{
public:
/*void print(int _a)
{
a = _a;
cout << "hello a!"<<a<< endl;
}*/
private:
int c;
protected:
};
int main()
{
child3 oop;
parent oop1;
system("pause");
return 0;
}
这里不会报错,但是只要涉及到使用a则必须加int parent:::a=100,否则会提示无法解析的外部符号 "public: static int parent::a" (?a@parent@@2HA),例如:
#include <iostream>
using namespace std;
class parent
{
public:
#if 1
void print(void)
{
cout << "parent a=:"<<a<< endl;
}
#endif
public:
static int a;
private:
int b;
protected:
int d;
};
//int parent::a = 100;
class child3 : public parent
{
public:
void print(int _a)
{
a = _a;
cout << "hello a!"<<a<< endl;
}
private:
int c;
protected:
};
int main()
{
child3 oop;
oop.a = 10;
parent oop1;
system("pause");
return 0;
}