12.9-3

m_company = new char[len+1];
如果m_company = new char[len];~stock时发生错误!!!

Stock::Stock(char* co, long n , double pr )
{
	int len = strlen(co);
	m_company = new char[len+1];
	strcpy_s(m_company, len+1 , co);
	m_shares = n;
	m_share_val = pr;
}

这里是引用

#ifndef STOCK20_H_
#define STOCK20_H_

class Stock
{
public:
	Stock();
	Stock(char* co, long n = 0, double pr = 0.0);
	~Stock();
	void buy(long num, double price);
	void sell(long num, double price);
	void update(double price);
	void show()const;
	const Stock & topval(const Stock&s)const;
	friend std::ostream& operator<<(std::ostream &os, Stock&);
protected:
private:
	//std::string company;
	char*  m_company;
	int	   m_shares;
	double m_share_val;
	double m_total_val;
	void set_tot(){ m_total_val = m_shares*m_share_val; }
};
#endif	

#include <iostream>
#include "stock20.h"

Stock::Stock()
{
	m_company = new char[1];
	m_company[0] = '\0';
	m_shares = 0;
	m_share_val = 0;
	this->set_tot();
}
Stock::Stock(char* co, long n , double pr )
{
	int len = strlen(co);
	m_company = new char[len+1];
	strcpy_s(m_company, len+1 , co);
	m_shares = n;
	m_share_val = pr;
	this->set_tot();
}
Stock::~Stock()
{
	delete[] m_company;
}
const Stock & Stock::topval(const Stock&s)const
{
	return *this;
}
std::ostream& operator<<(std::ostream &os, Stock&s)
{
	os << "s.m_company:" << s.m_company << " "<< "m_total_val: " << s.m_total_val;
	return os;
}

#include <iostream>
#include "stock20.h"
using namespace std;

void main()
{
	cout << "Using constructors to create new object\n";
	/*Stock stock;
	cout << stock<<endl;*/
	Stock stock1("Company A", 1, 2);
	cout << stock1<<endl;
	cout<<"hello.."<<endl;
	system("pause");
	return ;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值