【问题标题】:Strange behaviour default constructor奇怪的行为默认构造函数
【发布时间】:2018-11-17 02:06:32
【问题描述】:

有人能解释一下为什么在创建 temp 之后的重载函数中, temp.x 变成 2,而 temp.y 变成 1 吗?默认构造函数没有参数,因此 temp.x 和 temp.y 不应为 0 或具有奇怪的数字?
谢谢!

// overloading operators example
#include <iostream>
using namespace std;

class CVector {
  public:
    int x,y;
    CVector () {};
    CVector (int a,int b) : x(a), y(b) {}
    CVector operator + (const CVector&);
};

CVector CVector::operator+ (const CVector& param) {
  CVector temp;
  cout << " x: -> " << temp.x << " <-";
  cout << " y: -> " << temp.y << " <-\n";
  temp.x = x + param.x;
  temp.y = y + param.y;
  return temp;
}

int main () {
  CVector foo (3,1);
  CVector bar (1,2);
  CVector result;
  result = foo + bar;
  cout << result.x << ',' << result.y << '\n';
  return 0;
}

Result: x:-> 2 <- y: -> 1 <-
        4,3

【问题讨论】:

    标签: c++ class constructor overloading default


    【解决方案1】:

    默认情况下,成员变量已构造但未初始化。这意味着默认构造的 CVector 对象将具有未初始化的 x 和 y 成员,具有 indeterminate 值。

    由于您打印了那些不确定的值,您将拥有undefined behavior。

    如果您希望默认构造函数设置特定值(例如零),那么您必须明确地进行(例如在构造函数初始化列表中):

    CVector () : x(0), y(0) {}
    

    【讨论】:

      【解决方案2】:

      为了补充一些程序员老兄所说的,您还可以在多参数构造函数中使用默认初始化:

      CVector (int a = 0, int b = 0) : x(a), y(b) {}
      

      如果您创建了默认的 CVector(),它将始终将成员设置为 0,但您仍然可以使用相同的构造函数完成 CVector(5,5)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-24
        相关资源
        最近更新 更多