64,654
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class Father{
public:
int a;
Father(int x){}
};
class Child:public Father{
public:
Child(int x):Father(x-1){
a=x;
}
};
int main(){
Child test(5);
cout<<test.a<<endl;
Father* x=static_cast<Father*>(&test);
cout<<x->a<<endl;
return 0;
}
#include <iostream>
using namespace std;
class Father{
public:
int a;
Father(int x){
a = x;
cout<<a<<endl;
}
void display(){
cout<<a<<endl;
}
};
class Child:public Father{
public:
// int a ; //同名变量
Child(int x):Father(x-1){
cout<<a<<endl;
}
};
int main()
{
Child test(5);
return 0;
}
#include <iostream>
using namespace std;
class Father{
public:
int a;
Father(int x){
a = x;
cout<<a<<endl;
}
void display(){
a+=10;
cout<<a<<endl;
}
};
class Child:public Father{
public:
int a ; //增加变量
Child(int x):Father(x-1){
a=x;
cout<<a<<endl;
}
};
int main()
{
Child test(5);
cout<<test.a<<endl;
//c此处调用的是共享代码区间,故display中访问的是父类的成员变量a,子类成员a不变
test.display(); //输出的是父类变量a
Father* x=static_cast<Father*>(&test);
cout<<x->a<<endl; //与前面的结果想验证
cout<<test.a<<endl; //子类中的成员a并没有改变
return 0;
}
#include "stdafx.h"
#include <iostream>
using namespace std;
class Father{
public:
int a;
Father(int x){a = x;} //构造函数
};
class Child:public Father{
public:
int a ; //增加变量
Child(int x):Father(x-1){
a=x;
}
};
int main()
{
Child test(5);
cout<<test.a<<endl;
Father* x=static_cast<Father*>(&test);
cout<<x->a<<endl;
return 0;
}
test.Father::a;
class Father{
public:
int a;
Father(int x):a(x)
{ //a = x;
//cout << x << a << endl;
}
~Father(){ cout << a << endl; }
};
class Child:public Father{
public:
Child(int x):Father(x-1){
a=x;
}
};
int main()
{
Child test(5);
cout<<test.a<<endl;
Father* x=static_cast<Father*>(&test);
cout<<x->a<<endl;
return 0;
}