一个简单的c++程序

王朝知道·作者佚名  2011-12-10
窄屏简体版  字體: |||超大  
 
分類: 電腦/網絡 >> 程序設計 >> 其他編程語言
 
問題描述:

#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显示一下结果

-*********** 和 -***********

为什么?我在2000和vc6下运行的

參考答案:

你的构造函数写错了

应该是

tree::tree(int size)

{

this->size = size;

}

不写this的话,你声明类内部变量的时候换个名字就行了

比如int _size;

这样构造函数就是:

你的构造函数写错了

应该是

tree::tree(int size)

{

_size = size;

}

小贴士:① 若网友所发内容与教科书相悖,请以教科书为准;② 若网友所发内容与科学常识、官方权威机构相悖,请以后者为准;③ 若网友所发内容不正确或者违背公序良俗,右下举报/纠错。
 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航