C++开发初级


1012 浏览 5 years, 3 months

3.1.3 提供多个构造函数

版权声明: 转载请注明出处 http://www.codingsoho.com/
提供多个构造函数

在一个类中可以提供多个构造函数。所有构造函数名称相同(类名),但不同构造函数具有不同数量的参数或者不同的参数类型。在C++中,如果多个函数具有相同的名称,当调用的时候编译器会选择参数类型匹配的那个函数。这叫做重载,后面将详细讨论。

在SpreadsheetCell类中,编写两个构造函数是有益的:一个采用double初始值,一个采用string初始值。下面的类定义具有两个构造函数:

class SpreadsheetCell
{
 public:
  SpreadsheetCell(double initialValue);
  SpreadsheetCell(string initialValue);
};

代码取自 SpreadsheetCellCtors\SpreadsheetCell.h

下面是第二个构造函数的实现:

SpreadsheetCell::SpreadsheetCell(string initialValue)
{
  setString(initialValue);
}

代码取自 SpreadsheetCellCtors\SpreadsheetCell.cpp

下面是使用两个不同构造函数的代码:

  SpreadsheetCell aThirdCell("test"); // uses string-arg ctor
  SpreadsheetCell aFourthCell(4.4);    // uses double-arg ctor
  SpreadsheetCell* aThirdCellp = new SpreadsheetCell("4.4"); // string-arg ctor
  cout << "aThirdCell: " << aThirdCell.getValue() << endl;
  cout << "aFourthCell: " << aFourthCell.getValue() << endl;
  cout << "aThirdCellp: " << aThirdCellp->getValue() << endl;

  delete aThirdCellp;
  aThirdCellp = nullptr;

代码取自 SpreadsheetCellCtors\SpreadsheetCellTest.cpp

当具有多个构造函数时,在一个构造函数中执行另一个构造函数的想法很诱人。例如,您或许想以下面的方式让String构造函数调用double构造函数:

SpreadsheetCell::SpreadsheetCell(string initialValue)
{
  SpreadsheetCell(stringToDouble(initialValue));
}

这看上去是合理的。因为可以在类的一个方法中调用另一个方法。这段代码可以编译、链接并运行,但是结果并非您预期的那样。显式调用SpreadsheetCell构造函数实际上新建了一个SpreadsheetCell类型的临时未命名对象,而并不是像您预期的那样调用构造函数以初始化对象。

C++11引入了一个名为委托构造函数(delegating constructors)的新特性,允许构造函数调用同一个类的其他构造函数。这一内容将在本章讨论。