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 ;
}