请教各位,如何实例化带参数构造函数的成员对象

pobomud 2008-10-24 01:26:46
假定有2个类,类A构造函数声明为 A(char *strA); 类B构造函数声明为 B(char *strB);
class A
{
public:
A(char *strA):m_strA(strA){}
void displayA();
private:
char* m_strA;
}

void A::displayA()
{
cout<<m_strA<<endl;
}

class B
{
public:
B(char *strB)):m_strB(strB){}
private:
char *m_strB;
A a(m_strB); //这里编译出错,因为实例化B类前m_strB没有分配内存,};
//若要达到这个目的,请问该如何实例化这个带参数的对象???
}

int main()
{
B b("测试");
b.a.displayA();
return 0;
}
...全文
448 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
muyu_baiaixing 2008-10-24
  • 打赏
  • 举报
回复
可不可以将 A的构造函数直接定义成 默认参数的构造函数

在B中 就可以不用直接初始化A 的对象

因为先调用A的构造函数,然后才构造B
maplele20 2008-10-24
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 pobomud 的回复:]
C/C++ code

//请问除了用参数初始化列表,还有其他方法吗?

void B::B(char *strB)
{
m_strB = strB;
a(strB); //这里这样是不对的,有其他方法吗?
}



void B::B(char *strB)
{
m_strB = strB;
a = A(strB); //A中需要重载=
}
pobomud 2008-10-24
  • 打赏
  • 举报
回复

//请问除了用参数初始化列表,还有其他方法吗?

void B::B(char *strB)
{
m_strB = strB;
a(strB); //这里这样是不对的,有其他方法吗?
}
pobomud 2008-10-24
  • 打赏
  • 举报
回复

//请问除了用参数初始化列表,还有其他方法吗?

B::B(char *strB)
{
m_strB = strB;
a(strB); //这里这样是不对的,有其他方法吗?
}
chenzhp 2008-10-24
  • 打赏
  • 举报
回复
在初始化列表里面初始化,就像飞雪大侠所说
baihacker 2008-10-24
  • 打赏
  • 举报
回复
#include <iostream>
using namespace std;
class A
{
public:
A(char *strA):m_strA(strA){}
void displayA();
private:
char* m_strA;
} ;

void A::displayA()
{
cout <<m_strA <<endl;
}

class B
{
public:
B(char *strB):m_strB(strB),a(strB){}
private:
char *m_strB;
A a; //这里编译出错,因为实例化B类前m_strB没有分配内存,};
//若要达到这个目的,请问该如何实例化这个带参数的对象???
} ;

int main()
{
B b("测试");
// b.a.displayA(); //a是私有的哟
return 0;
}

64,646

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧