我在fixed.cpp中创建了一个类声明文件作为fixed.hpp和类定义。当我在主函数中创建一个对象时。编译器告诉我该类未声明。但我想我做到了。任何想法或帮助?谢谢。
这是main.cpp:
#include <iostream>
#include <istream>
#include <ostream>
#include <sstream>
#include <stdexcept>
#include "test.hpp"
#include "fixed.hpp"
int main(int argc, char *argv[])
{ using namespace std;
fixed f1;
cout<<f1.value()<<endl;
}
这是fixed.hpp:
#ifndef FIXED_HPP_
#define FIXED_HPP_
typedef float value_type ;
class fixed
{
public:
fixed();
fixed(value_type integer, value_type fraction);
fixed(double val);
void as_string();
value_type integer();
value_type fraction();
value_type value();
static const int places=4;
static const int places10=10000; //scale factor
private:
value_type integer_;
value_type fraction_;
//value_type result_;
};
这是fixed.cpp:
#include "fixed.hpp"
#include <iostream>
#include <ostream>
#include <stdexcept>
#include <string>
using namespace std;
//static const value_type fixed::places(4);
//static const value_type fixed::places10(10000);
fixed::fixed():integer_(0), fraction_(0){}
fixed::fixed(value_type integer,value_type fraction):integer_(integer), fraction_(fraction)
{try
{
if (fraction_ <0)
throw invalid_argument("Invalid argument. Must be positive.");
}
catch (exception& e)
{
cout <<"\n"<< e.what() << endl;
}
while (fraction_>= places10)
{
if(int(fraction_)%10 >=5 && fraction_< (places10*10) )
fraction_=fraction_/10+1;
else
fraction_/=10;
}
//result_ = integer_ + fraction_/places10; //??
}
fixed::fixed(double val):integer_(int (val)), fraction_( (val- int(val))*places10)
{ if (val <0)
{ val = val*(-1);
if ( int(val*places10*10)%10>=5)
fraction_ = (fraction_*(-1) +1)*(-1);
}
else
{
if (int(val*places10*10)%10>=5)
fraction_ = fraction_ +1;
}
//result_ = integer_ + fraction_/places10; //??
}
void fixed::as_string()
{ string str;
string str2;
while( (int(integer_)/10) >=0 and int(integer_)>0 )
{
str.push_back(int(integer_)%10 + 48);
integer_ = integer_/10;
//cout<<str<<endl;
}
//cout<<"String format: "<<str<<endl;
reverse(str.begin(), str.end());
//cout<<"Reversed format: "<<str<<endl;
str.push_back('.');
//cout<<"New string: "<<str<<endl;
while( (int(fraction_)/10 )>=0 and int(fraction_)>0)
{
str2.push_back(int(fraction_)%10 + 48);
fraction_ = fraction_/10;
//cout<<str<<endl;
}
//cout<<"String format: "<<str<<endl;
reverse(str2.begin(), str2.end());
str.append(str2);
cout<<"String representation: "<<str<<endl;
}
value_type fixed::value()
{
return integer_ + fraction_/places10;
}
value_type fixed::integer()
{
return integer_;
}
value_type fixed::fraction()
{
return fraction_;
}