My first c++ class : Tree

2103 ワード

A simple c++ class, Contain three file:
 
/*
 * Tree.h
 *
 *  Created on: Aug 23, 2009
 *      Author: sai
 */

#ifndef TREE_H_
#define TREE_H_

#include 

using namespace std;

class Tree {
	int height; // the tree's height
public:
	Tree(int initialHeight);
	virtual ~Tree();
	void grow(int years);
	void printsize();

	/**
	 * over loade << operator like this:
	 * friend ostream& operator<< (ostream& os, const Tree& tree) const;
	 *
	 * got error:non-member function ‘std::ostream& operator<<(std::ostream&, const Tree&)’ cannot have cv-qualifier
	 */

	friend ostream& operator<< (ostream& os, const Tree& tree);
};

#endif /* TREE_H_ */
/*
 * Tree.cpp
 *
 *  Created on: Aug 23, 2009
 *      Author: sai
 */
#include 

#include "Tree.h"

using namespace std;

Tree::Tree(int initialHeight) {
	height = initialHeight;
}

Tree::~Tree() {
	// DO NOTHING
}

void Tree::grow(int years) {
	height += years;
}

void Tree::printsize() {
	cout << "Tree's height is :" << height;
}

ostream& operator<< (ostream& out, const Tree& tree){
	out << "Tree's height is :" <<  tree.height;
	return out;
}
//============================================================================
// Name        : welcome.cpp
// Author      : sai
// Version     :
// Copyright   : copyright 2009, sai zeng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include 

#include "Tree.h"

using namespace std;

int main() {
	cout << "Welcome CPP developer" << endl; // prints Welcome CPP developer

	/** test class Tree*/
	Tree r(30);
	r.printsize();
	cout << endl;

	r.grow(23);
	r.printsize();
	cout << endl;

	cout << r << endl;

	return 0;
}

 
output:
Welcome CPP developer
Tree height is :30
Tree height is :53
Tree height is :53

sai@