我通过阅读Stephen Prata的“c ++ Primer Plus”一书来学习c ++。在第10章中,有一个示例有三个(代码清单10.4到10.6)文件(stock10.h(包含类声明),stock10.cpp(包含成员函数定义)和usestok1.cpp(包含调用函数))。
当我使用命令
一起编译它们时g++ -o stock usestok1.cpp stock10.cpp
我收到以下错误
/usr/lib/gcc/x86_64-pc-linux-gnu/7.2.0/../../../../lib/Scrt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
文件'usestok1.cpp'从工作目录中消失。我哪里出错?
文件包含的代码:
第一个(stock10.h)有类声明。
//stock10.h
#ifndef STOCK10_H_
#define STOCK10_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:
stock();
stock(const std::string& co,long n=0,double pr=0);
~stock();
void buy(long num,double price);
void sell(long num,double price);
void update(double price);
void show();
};
#endif
第二个(stock10.cpp)具有类成员定义
//stock10.cpp
#include <iostream>
#include "stock10.h"
stock::stock()
{
std::cout<<"Default constructor invoked";
company="no name";
shares=0;
share_val=0.0;
total_val=0.0;
}
stock::stock(const std::string& co,long n,double pr)
{
std::cout<<"Consturctor using"<<co<<" called\n";
company=co;
if(n<0)
{
std::cout<<"Number of shares cannot be negative;"<<company<<" shares set to 0.\n";
shares=0;
}
else shares=n;
share_val=pr;
set_tot();
}
stock::~stock()
{
std::cout<<"Bye, "<<company<<"\n";
}
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 shares sold can't be negative. "<<" Transaction is aborted.\n";
}
else if(num>shares)
{
cout<<"You can't sell any more shares. 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()
{
using std::cout;
using std::ios_base;
using std::endl;
ios_base::fmtflags orig=cout.setf(ios_base::fixed,ios_base::floatfield);
std::streamsize prec=cout.precision(3);
cout<<"Company : "<<company<<endl;
cout<<"Shares : "<<shares<<endl;
cout.precision(2);
cout<<"total Worth : $"<<total_val<<endl;
cout.setf(orig,ios_base::floatfield);
cout.precision(prec);
}
最后一个(usestok1.cpp)具有调用函数
#include <iostream>
#include "stock10.h"
int main()
{
{
using std::cout;
cout << "Using constructors to create new objects\n";
stock stock1("NanoSmart", 12, 20.0);
stock1.show();
stock stock2 = stock ("Boffo Objects", 2, 2.0); // syntax 2
stock2.show();
cout << "Assigning stock1 to stock2:\n";
stock2 = stock1;
cout << "Listing stock1 and stock2:\n";
stock1.show();
stock2.show();
cout << "Using a constructor to reset an object\n";
stock1 = stock("Nifty Foods", 10, 50.0);
cout << "Revised stock1:\n";
stock1.show();
cout << "Done\n";
}
return 0;
}