C++ GOTCHA 3

Last_Dodo 2002-01-23 11:27:57
1. Sometimes the following code seems to work just fine. Other times it crashes mysteriously. At other times the system seems sluggish. Why?
class Table
{
public:
Table(int sz);
...
private:
int *memory;
int size;
...
};

Table::Table(int sz):size(sz),memory(new int[size])
{
...
}

int main()
{
Table t(128);
return 0;
}

2. which f is called in the code below, and why?
class C
{
public:
int f(char *) { return 3; }
float f(int *) { return 3.14159; }
};
int main()
{
C x;
float g;
g = x.f(0); // what happens?
cout << g << endl;
return 0;
}

3. Explain the compiler error message generated by this code:
struct S {
int &ref;
S();
};
int main()
{
S x,y;
x = y; // illegal, why?
return 0;
}
...全文
130 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
thisisxutao 2002-01-24
  • 打赏
  • 举报
回复
虚心学习....
vcmfc 2002-01-24
  • 打赏
  • 举报
回复
感谢albert_ywy(北方的狼),不然回复不了第4个贴子。
vcmfc 2002-01-24
  • 打赏
  • 举报
回复


3.你的S::&ref未进行初始化,你应该知道,C++的引用一定义就要进行初始化。所以编译器一定会提醒你这个方面的错误信息。

albert_ywy 2002-01-24
  • 打赏
  • 举报
回复

插一腿

vcmfc 2002-01-24
  • 打赏
  • 举报
回复

2.编译错误,因为产生ling模两可的状态,编译器无法决定。


vcmfc 2002-01-24
  • 打赏
  • 举报
回复
错误更正:

]),但系统实际上还是先memory(new int[size]),因为你的成员在int *memory在int size顺序之前,而此时你的size的值又未确定,所,有时new出一个相当大的memory,因此有时相当不稳定的原因。

vcmfc 2002-01-24
  • 打赏
  • 举报
回复
1.有一种可能:由于你的类的声明顺序与member init list不一样,所以问题就可来了,如下解释:
由于你的类的成员对象顺序是int *memory;->int size;而你的member init list是:size(sz),memory(new int[size]),但系统实际上还是还memory(new int[size]),些时你的size的值未确定,因此,有时new以一个相当大的memory,所以有时相当不稳定的原因。

两种改法:size(sz),memory(new int[sz]);

在使用权member init list请遵守按成员对象的顺序来进行初始,你这个就是违反了这一条。

老熊宝宝 2002-01-23
  • 打赏
  • 举报
回复
还要看看。

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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