论友们帮看看,这个程序运行不了。

woshuo123mutouren 2009-06-22 06:04:20
大家帮看看哪错了。运行不了

#include <iostream.h>
class cB
{
public:
cB()
{
B_value=1;
cout<<"construct cB.B_value="<<B_value<<endl;
}
cB(int v=7)
{
B_value=v;
cout<<"construct cB.B_value="<<B_value<<endl;
}
~cB()
{
cout<<"destruct cB.B_value="<<B_value<<endl;
}
protected:
int B_value;
};
class cA
{
protected:
int a;
cB b;
public:
cA(int v1,int v2=3):b(v2)
{
a=v1;
cout<<"construct cA.a="<<a<<endl;
}
~cA()
{
cout<<"destruct cA."<<endl;
}
};
void main()
{
cA a1(5,10);
cA a2(5);
cB b1(18);
cB b2;
}
...全文
70 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Jalien 2009-06-22
  • 打赏
  • 举报
回复
就是说本来没有参数可以调用cb(int v=7)这个(默认参数为7),(单个的cb(int v=7)没错)但是又有cb()编译器看到两个都可以调用就傻了,所以决定不调用,报错,这就是二义性。[Quote=引用 3 楼 woshuo123mutouren 的回复:]
请问,您是说
cB(int v=7)
{
B_value=v;
cout < <"construct cB.B_value=" < <B_value < <endl;
}
这段有错误么?能帮我仔细解释下么。我有点没听懂,麻烦您了
[/Quote]
Walf_ghoul 2009-06-22
  • 打赏
  • 举报
回复
你的构造函数有了一个cB()了如果你的这个cB(int v)给了v一个默认值的话,调用cB()时,就会产生二义性,不知道调用那个了
woshuo123mutouren 2009-06-22
  • 打赏
  • 举报
回复
谢谢你。我懂了
woshuo123mutouren 2009-06-22
  • 打赏
  • 举报
回复
请问,您是说
cB(int v=7)
{
B_value=v;
cout<<"construct cB.B_value="<<B_value<<endl;
}
这段有错误么?能帮我仔细解释下么。我有点没听懂,麻烦您了
Walf_ghoul 2009-06-22
  • 打赏
  • 举报
回复

#include <iostream>
using namespace std;
class cB
{
public:
cB()
{
B_value=1;
cout <<"construct cB.B_value=" <<B_value <<endl;
}
cB(int v) //这儿不能给默认值
//cB(int v=7)
{
B_value=v;
cout <<"construct cB.B_value=" <<B_value <<endl;
}
~cB()
{
cout <<"destruct cB.B_value=" <<B_value <<endl;
}
protected:
int B_value;
};
class cA
{
protected:
int a;
cB b;
public:
cA(int v1,int v2=3):b(v2)
{
a=v1;
cout <<"construct cA.a=" <<a <<endl;
}
~cA()
{
cout <<"destruct cA." <<endl;
}
};

int main()
{
cA a1(5,10);
cA a2(5);
cB b1(18);
cB b2;
return 0;
}

「已注销」 2009-06-22
  • 打赏
  • 举报
回复
#include <iostream>

using namespace std;

class cB
{
public:
cB()
{
B_value = 1;
cout << "construct cB.B_value=" << B_value << endl;
}
cB(int v)
{
B_value = v;
cout << "construct cB.B_value=" << B_value << endl;
}
~cB()
{
cout << "destruct cB.B_value=" << B_value << endl;
}
protected:
int B_value;
};

class cA
{
protected:
int a;
cB b;
public:
cA(int v1, int v2 = 3): b(v2)
{
a = v1;
cout << "construct cA.a=" << a << endl;
}
~cA()
{
cout << "destruct cA." << endl;
}
};

int main()
{
cA a1(5, 10);
cA a2(5);
cB b1(18);
cB b2;
return 0;
}


cB(int v)
{
B_value = v;
cout << "construct cB.B_value=" << B_value << endl;
}

别用默认参数了,二义性

65,210

社区成员

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

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