一段测试C++类与对象的代码

#include<iostream>
#include<string>

//这部分应该放到头文件中
class Stock
{
private:
	std::string company;
	long shares;
	double share_val;
	double total_val;
	void set_val() { total_val = shares * share_val; } //或者可以用inline内联函数来代替
public:
	void show_info();
	void update();
	double total() const;
	const Stock & topval(const Stock &) const; //找出较大的股票信息,引出this指针
	Stock operator+(const Stock&) const; //重载+运算符,传引用比传值效率高,但是返回的是局部变量,所以只能返回副本,不能返回引用
	Stock operator*(double) const; //重载*运算符,格式为Stock*double
	friend Stock operator*(double, const Stock&); //友元函数(放在类声明中),*运算符的另一种重载,用于double*Stock
	Stock(const std::string &, long, double); //构造函数,这里如果给了每一项的default,在函数定义的时候又给一遍,会出现重定义错误
	Stock();//默认构造函数,可以声明一个什么都没有的Stock对象
	~Stock();//析构函数原型,只能是这一种,没有参数
};

int main()
{
	using namespace std;
	Stock Total,TEST;
	Stock HUST = { "Hust",500,20 };
	Stock WHU = { "WHU",500,15 };

	Total = HUST + WHU;
	TEST = 2 * HUST;
	TEST = TEST * 2;

	cout << WHU.total() << endl;
	cout << HUST.total() << endl;
	cout << Total.total() << endl;
	cout << TEST.total() << endl;

	return 0;
}

//这部分应该放到另外一个cpp文件中,将接口与实现细节分隔开来
void Stock::show_info()
{
	using std::cout;
	using std::endl;

	cout << "Company: " << company << endl;
	cout << "Shares: " << shares << endl;
	cout << "Value of Share: " << share_val << endl;
	cout << "Total Value: " << total_val << endl;
}

void Stock::update()
{
	using namespace std;
	long val;

	cout << "Enter the new price of stock: ";
	cin >> val;

	share_val = val;
	set_val();
}

inline double Stock::total() const //内联函数,节省时间
{
	return total_val;
}

const Stock & Stock::topval(const Stock & s) const
{
	if (s.total_val > total_val)
		return s;
	else
		return *this; //this指针指向使用该方法的对象
}

Stock Stock::operator+(const Stock& t) const
{
	Stock total;
	total.total_val = total_val + t.total_val;
	return total;
}

Stock Stock::operator*(double n) const
{
	Stock Temp;
	Temp.total_val = (this->total_val) * n;
	return Temp;
}

Stock operator*(double m, const Stock& t) //友元函数不需要使用类限定符Stock::
{
	Stock temp;
	temp.total_val = t.total_val * m;
	return temp;
}

Stock::Stock(const std::string & co, long n = 0, double pr = 0.0) //构造函数定义
{
	company = co;

	if (n < 0)
	{
		std::cerr << "Number of shares can't be negative;"
			<< company << " shares set to 0.\n";
		shares = 0;
	}
	else
		shares = n;
	share_val = pr;
	set_val();
}

Stock::Stock(){} //默认构造函数定义

Stock::~Stock()
{
	using std::cout;

	cout << "Now we are using ~Stock(), bye, " << company << "\n";//用一个输出语句看看在哪用的析构函数
}


//下面是测试函数,不需要时候注释掉
/*void test(int&);
int main()
{
	using namespace std;

	int a = 5;
	int &b = a;

	test(b); //这里传递的不是引用,是变量

	return 0;
}

void test(int& t)
{
	using namespace std;
	cout << "& has been passed here. t is " << t << endl;
}*/

猜你喜欢

转载自blog.csdn.net/o707191418/article/details/84314907