c++ - 关于构造函数和运算符的一些基本问题

标签 c++ constructor operators

抱歉,如果这个问题听起来太基础了,但我想知道这段代码中到底发生了什么(Point3d 是我自己的实现):

int main()
{
    Point3d a(1,2,3);
    Point3d b(11,12,13);
    Point3d c = a+b;
    Point3d d = a;
    Point3d e;

    return 0;
}

所以在运行上面的代码之后,函数将按以下顺序调用:

Point3d (const float x, const float y, const float z) // a
Point3d (const float x, const float y, const float z) // b
Point3d () //since I created a new object in operator+
operator+ (const Point3d& rhs) //a+b
Point3d (const Point3d& rhs) //the copy constructor for d = a
Point3d () //e

我注意到了一些事情:

  1. 没有为c调用构造函数
  2. operator= 永远不会被调用(但是,如果我将赋值和实例声明放在不同的行中,operator= 就会被调用)

我观察到的是否超出预期?如果是这样,为什么从未调用过 operator=

附言我的 operator+ 返回一个对象而不是一个引用(Point3d 而不是 Point3d&),我认为这是正确的吗?

最佳答案

  1. no constructor is called for c

很可能是由于 Return Value Optimization .

  1. operator= is never called

因为显示的行都没有执行任务,只有构造。在声明 在同一语句中分配对象的行中使用 = 只是复制构造的“语法糖”。

Point3d c = a+b; // aka: Point3d c(a+b);
Point3d d = a;   // aka: Point3d d(a);

However, if I put the assignment and instance declaration in different lines, operator= is called

是的,如果单独的语句(不是行)用于声明和赋值,则使用operator=

关于c++ - 关于构造函数和运算符的一些基本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47047485/

相关文章:

c++ - 按值传递临时对象作为参数 - 是否调用复制构造函数?

C 按位逻辑运算难题

c++ - 这个 C++/C++11 结构是什么意思?

c++ - 声明指向不同字符串的二维指针数组(在二维数组中)

c++ - 如何在 c++03 中获得模板参数的最精确表示?

c - F = (9/5 * C) + 32 和 F = (C *9/5) + 32 有什么区别?优先?

c++ - 如何使用 C++ 17 检查 operator != 是否存在模板参数?

c++ - std::vector new 内存不足

java - 无法使用 Class.forName() 实例化类

java - 何时创建使用实例方法与何时传递对象引用?