更新时间:2023-02-15 17:12:04
是的,你可以。
您当然可以通过 - >
运算符访问对象的公共成员。
我可以我不知道你为什么会遇到运行时故障,但我可能会怀疑你正在调用无效指针的方法(或访问数据)(例如,传递的对象仍然存活 - 在你访问它时还没有被释放?)。
[更新]
#include < iostream >
使用 命名空间标准;
class X
{
public :
int ver;
X( int v):ver(v){}
};
class Y
{
X * px;
public :
Y(X * pObj):px(pObj){}
void showXVer(){cout<< x version:<< px-> ver<< endl;}
};
int main()
{
X x( 42 );
Y y(& x);
y.showXVer();
}
[/ Update]
是的,只要Y类有一个Class X类型的成员变量。#include < cstdio >
class class1
{
public :
bool 已初始化;
bool otherFuncUsed;
class1()
{
initialized = true ;
otherFuncUsed = false ;
}
void sampleFunc()
{
otherFuncUsed = true ;
}
};
class class2
{
public :
class1 memberClass;
class2()
{
printf( memberClass.otherFuncUsed =%d \\ n \\ n,memberClass.otherFuncUsed);
memberClass.sampleFunc();
printf( memberClass.otherFuncUsed =%d \ n,memberClass.otherFuncUsed) ;
}
};
int main()
{
class2 sampleVar;
}
内容已移至原始问题。
Hi..
This is what I want to do :
1. Pass an object pointer of a class (say X) to the constructor of another class(say Y).
Now my question is :
Can I access the public members of class X in member functions of class Y ? If possible then I want to know how..as it''s giving me some runtime failures.
Thankss in advance..!!
EDIT: Update to original question from the OP. [enhzflep]
This is what i wish to do :
Class X
{
public:
int ver;
}
class Y
{
y(X *obj)
{
}
void someMethod
{
cout<< obj.ver;
}
}
void main()
{
y obj1=new y();
y.someMethod;
}
Can this be done.??
Yes, you can.
You can access the public members of the object via the->
operator, of course.
I can''t know why are you getting runtime failures, however I might suspect you are calling methods (or accessing data) of an invalid pointer (e.g. is the passed object still alive - has not be released - while you are accessing it?).
[Update]#include <iostream> using namespace std; class X { public: int ver; X(int v):ver(v){} }; class Y { X * px; public: Y(X * pObj):px(pObj){} void showXVer(){ cout << "x version: " << px->ver << endl;} }; int main() { X x(42); Y y(&x); y.showXVer(); }
[/Update]
Yes, so long as class Y has a member variable of type Class X.#include <cstdio> class class1 { public: bool initialized; bool otherFuncUsed; class1() { initialized = true; otherFuncUsed = false; } void sampleFunc() { otherFuncUsed = true; } }; class class2 { public: class1 memberClass; class2() { printf("memberClass.otherFuncUsed = %d\n", memberClass.otherFuncUsed); memberClass.sampleFunc(); printf("memberClass.otherFuncUsed = %d\n", memberClass.otherFuncUsed); } }; int main() { class2 sampleVar; }
Content moved to original question.