首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

class中函数重载的long与int的有关问题

2013-12-06 
class中函数重载的long与int的问题定义了一个class Money,如下所示,class Money{public:Money(long dollar

class中函数重载的long与int的问题
定义了一个class Money,如下所示,


class Money
{
public:
Money(long dollars, int cents);
// Initializes the object to its value represents an amount with the
// dollars and cents given by the arguments. If the amount is negative,
// then both dollars and cents must be negative.
Money(long dollars);
// Initializes the object so its value represents $dollars.00.
Money(double dollars);
// Initializes the object so its value represents 100*dollars cents.
Money();
// Initializes the object so its value represents $0.00.
double get_value() const;
// Precondition: The calling object has been given a value.
// Returns the amount of money recorded in the data of the calling object.
void input(istream& ins);
// Precondition: If ins is a file input stream, then ins has already been
// connected to a file. An amount of money, including a dollar sign, has been
// entered in the input stream ins. Notation for negative amounts is -$100.00.
// Postcondition: The value of the calling object has been set to
// the amount of money read from the input stream ins.
void output(ostream& outs) const;
// Precondition: If ins is a file input stream, then ins has already been
// connected to a file. 
// Postcondition: A dollar sign and the amount of money recorded
// in the calling object have been sent to the output stream outs.
private:
long all_cents;

};


函数比较多,但是有问题的就是这两个构造函数:


Money::Money(long dollars):all_cents(dollars * 100)
{
// Body intentionally blank.
}

Money::Money(double dollars)
// Initializes the object so its value represents 100*dollars cents.
{
all_cents=static_cast<long>(100*dollars);
}


然而,在main()函数里使用语句
Money my_amount(10);
时,编译器给出错误说
ambiguous call to overloaded function
这个是怎么回事?如何解决?
[解决办法]
试试
Money my_amount(10L);
//or 
Money my_amount(10.0);

[解决办法]
1)explicit 一下,看行不。
2)定义一个long double 看行不。
[解决办法]



引用:
Quote: 引用:

试试
Money my_amount(10L);
//or 
Money my_amount(10.0);


好诡异啊好诡异,编了另一个类似的程序,竟然没有报错了……

你要相信:事出有因。 
[解决办法]
10 默认是int ,到long 跟到double 都需要一次转换.

编译器无法区分那个重载,就给你报错了.

热点排行