c++类函数
代码很长其实很简单请耐心这是c++ primer plus347348页的东西stock00.h/*头文件*/#ifndef STOCK00_H_
#define STOCK00_H_
#include<string>
class Stock
{
private:
std::string company;
long shares;
double share_val;
double total_val;
void set_tot() { total_val = shares * share_val;}
public:
void acquire(const std::string & co, long n, double pr);
void buy(long num, double price);
void sell(long num, double price);
void update(double price);
void show();
};
#endif
stock00.cpp /*源码文件*/
#include<iostream>
#include"stock00.h"
void Stock::acquire(const std::string & co, long n, double pr)
{
company = co;
if(n < 0)
{
std::cout << "Number of shares can't be negative; "
<< company << " shares set to 0.\n";
shares = 0;
}
else
{
shares = n;
}
share_val = pr;
set_tot();
}
void Stock::buy(long num, double price)
{
if(num < 0)
{
std::cout << "Number of shares purchased can't be negative. "
<< "Transaction is aborted.\n";
}
else
{
shares += num;
share_val = price;
set_tot();
}
}
void Stock::sell(long num, double price)
{
using std::cout;
if(num < 0)
{
cout << "Number of share sold cant be negative. "
<< "Transaction is aborted.\n";
}
else if(num > shares)
{
cout << "You can't sell more than you have! "
<< "Transaction is aborted.\n";
}
else
{
shares -= num;
share_val = price;
set_tot();
}
}
void Stock::update(double price)
{
share_val = price;
set_tot();
}
void Stock::show()
{
std::cout << "Company: " << company
<< " Shares: " << shares << '\n'
<< " Share Price: $" << share_val
<< " Total Worth: $" << total_val << '\n';
}
这个set_tot()应该是内联函数吧因为它在声明中定义了
那几干函数都用了set_tot()
这个set_tot的代码都被写入那几个函数了吗
可是书上说没有写入啊而是函数调用
这几个本身都是内联函数。(希望你懂我的意思) 你的理解没错,set_tot()是内联函数,“调用内联函数”的意思就是调用内联函数替换后的代码。
此外,你的代码是书上抄的?void Stock::show()居然不是void Stock::show()const?这书按说不应该犯这种低级错误啊 仰望天上的光 发表于 2014-5-19 17:26 static/image/common/back.gif
你的理解没错,set_tot()是内联函数,“调用内联函数”的意思就是调用内联函数替换后的代码。
此外,你的代 ...
还没有讲const函数下一节就有了这是第一节
inline吗?现在好少看见这个关键字的使用了。因为编译器智能了就不用我们来自能了。
页:
[1]