
一个简单的c++程序
#include"stdio.h"classtree{intsize;public:tree(intsize);~tree();voidgrow(intyear);voi...
#include "stdio.h"
class tree{
int size;
public:
tree(int size);
~tree();
void grow(int year);
void printSize();
};
tree::tree(int size)
{
size = size;
}
tree::~tree(){
puts("inside tree destructor\n");
printSize();
}
void tree::grow(int year)
{
size += year;
}
void tree::printSize()
{
printf("tree height is %d\n", size);
}
main(){
puts("before opening brace");
{
tree t(12);
puts("after tree creation");
t.printSize();
t.grow(4);
puts("before closing brace");
}
puts("after closing brace");
}
输出时size显示一下结果
-858993460 和 -858993456
为什么?我在2000和vc6下运行的
这个this 不写不行吗?为什么在这里非要写?
这个好像和java很不相同来。 展开
class tree{
int size;
public:
tree(int size);
~tree();
void grow(int year);
void printSize();
};
tree::tree(int size)
{
size = size;
}
tree::~tree(){
puts("inside tree destructor\n");
printSize();
}
void tree::grow(int year)
{
size += year;
}
void tree::printSize()
{
printf("tree height is %d\n", size);
}
main(){
puts("before opening brace");
{
tree t(12);
puts("after tree creation");
t.printSize();
t.grow(4);
puts("before closing brace");
}
puts("after closing brace");
}
输出时size显示一下结果
-858993460 和 -858993456
为什么?我在2000和vc6下运行的
这个this 不写不行吗?为什么在这里非要写?
这个好像和java很不相同来。 展开
3个回答
展开全部
你的构造函数写错了
应该是
tree::tree(int size)
{
this->size = size;
}
你要清楚,赋值号前面的size是你class里面定义的size,后面的size是你函数的参数里面的size,两个是不同的,那你写的size=size,怎么能够区分呢?
所以要写成this->size=size; this->size就告诉编译器,是class里面定义的size,JAVA里面应该也不会不同。但是JAVA就不属于这个问题的范围了。你可以去问精通JAVA的人,但是C++就是这样的。
应该是
tree::tree(int size)
{
this->size = size;
}
你要清楚,赋值号前面的size是你class里面定义的size,后面的size是你函数的参数里面的size,两个是不同的,那你写的size=size,怎么能够区分呢?
所以要写成this->size=size; this->size就告诉编译器,是class里面定义的size,JAVA里面应该也不会不同。但是JAVA就不属于这个问题的范围了。你可以去问精通JAVA的人,但是C++就是这样的。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
你的构造函数写错了
应该是
tree::tree(int size)
{
this->size = size;
}
不写this的话,你声明类内部变量的时候换个名字就行了
比如int _size;
这样构造函数就是:
你的构造函数写错了
应该是
tree::tree(int size)
{
_size = size;
}
应该是
tree::tree(int size)
{
this->size = size;
}
不写this的话,你声明类内部变量的时候换个名字就行了
比如int _size;
这样构造函数就是:
你的构造函数写错了
应该是
tree::tree(int size)
{
_size = size;
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
java不用this是因为java语法不允许 size = size这种情况出现
C++必须说明是 this->size
否则,你怎么知道size是哪个
C++必须说明是 this->size
否则,你怎么知道size是哪个
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询