C++ 实例化 "Implicit"类对象

标签 c++ object constructor instantiation objectinstantiation

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/

相关文章:

c++ - 没有明确使用返回/退出的任何退出状态

java - 自动将构造的每个 Class 对象添加到 ArrayList 中

Javascript根据排序属性对树级别进行排序

C++ Try-Catch 语句未捕获异常

c++ - 在 C++ 中动态定义函数

类外的C++虚函数实现

c++ - 返回在transform中用lambda构造的对象

c++ - 构造函数被调用了多少次?

python - 防止在 Python 构造函数中创建对象

java - 是否可以在java中创建实例的同一行中调用方法