在其他类中创建一个类的对象 [英] make an object of one class in other class

查看:68
本文介绍了在其他类中创建一个类的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

喜。哦,对不起。我有问题了。

<前lang =cs> A
{
public
int 数据;
A( int d):data(d){}
};
class B
{

public
A s;
B(A e):s(e){}
};
int _tmain( int argc,_TCHAR * argv [])
{
A ins( 12 );
B ins1(ins);
return 0 ;上面代码中的
}



当一个对象想要制作时,我在B类中创建一个A类对象。构造函数应该调用。在行中

 A s; 



类A的构造函数应该调用。是?但是没有任何默认构造函数可以调用。我认为这一行是假的我应该写

 A s( 0 ); 



因为A类的构造函数有一个参数。但这是假的,并且

 A s; 



是真的。但我不知道为什么?

请帮帮我

谢谢

解决方案

不, A s; 是B类声明的一部分 - 在创建B实例之前,不构造实际的s成员。



B(A e):s(e){} line是B和B的构造函数:s(e)它的一部分是调用A(int)构造函数的初始化列表。


hi. oh i am sorry . i have question again.

class A
{
public:
    int data;
    A(int d):data(d){}
};
class B
{

public:
    A s;
    B(A e):s(e){}
};
int _tmain(int argc, _TCHAR* argv[])
{
    A ins(12);
    B ins1(ins);
    return 0;
}


in above code i make an object of class A in class B. when an object want to make . the constructor should call. in the line

A s;


the constructor of class A should call . yes? but there isn't any default constructor to call. i think this line is false and i should write

A s(0);


because the constructor of class A have an argument . but this is false and the

A s;


is true. but i don't know why ?
please help me
thanks

解决方案

No, the "A s;" is part of your "B" class declaration - the actual "s" member is not constructed until an instance of "B" is created.

The "B(A e):s(e){}" line is a constructor for "B" and the ":s(e)" part of it is the initialisation list where the "A(int)" constructor is called.


这篇关于在其他类中创建一个类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆