class Cents
{
private:
int m_nCents;
public:
Cents(int nCents) { m_nCents = nCents; }
// Overload cCents + int
friend Cents operator+(const Cents &cCents, int nCents);
int GetCents() { return m_nCents; }
};
// note: this function is not a member function!
Cents operator+(const Cents &cCents, int nCents)
{
return Cents(cCents.m_nCents + nCents);
}
int main()
{
Cents c1 = Cents(4) + 6;
std::cout << "I have " << c1.GetCents() << " cents." << std::endl;
return 0;
}
我不太清楚这个表达式
Cents(4)+6
排队
Cents c1 = Cents(4) + 6;
被评估。 是的,我知道我们正在分别为 Cents 和 int 类型的操作数重载运算符“+”。
据我了解,Censt(4) 是构造函数,对吧?所以当
Cents operator+(const Cents &cCents, int nCents)
{
return Cents(cCents.m_nCents + nCents);
}
调用 cCenst 是否成为对 Cents(4) 的引用?
来自行
return Cents(cCents.m_nCents + nCents);
可以推断 cCenst 是 Censt 类型的对象,因为我们通过成员选择运算符“.”访问 m_nCents。但是 Censt(4) 是构造函数而不是类对象。
对我来说,cCenst 引用 Cents(4) 似乎没有意义,因为它们不等价。
最佳答案
As I understand Censt(4) is the constructor, right?
不,不完全是。您从不直接调用构造函数,即使这种语法使它看起来有点像您这样做。
在这里,您正在构造一个 Censt
类型的临时对象,其构造函数参数为 4
。
更像这样想:
Censt x(4); // creates a `Censt` with name `x` from argument `4`
Censt(4); // creates a `Censt` with no name from argument `4`
这不是函数调用。
does cCenst become a reference to Cents(4)?
是的。
But Censt(4) is a constructor and not a class object.
同样,不。它是一个对象。
关于C++ 实例化 "Implicit"类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28385433/