跳到内容

类的自动转换与强制转换 ​

构造函数充当转换函数 ​

如果一个构造函数只接受一个参数(其余参数都有默认值),它就定义了一条从该参数类型到本类的隐式转换路径。编译器在需要本类对象、却拿到那个参数类型时,会自动调用这个构造函数做转换。

cpp
// weight.h —— 重量类,可从 double(磅)构造
#ifndef WEIGHT_H_
#define WEIGHT_H_
#include <iostream>

class Weight
{
private:
    static constexpr int LBS_PER_STONE = 14;
    int stone;          // 整石数
    double lbs;         // 总磅数
public:
    Weight();                       // 默认构造
    Weight(double lbsIn);           // 一个参数:可当转换函数
    Weight(int stn, double lbsIn);  // 两个参数:不能当转换函数
    void showLbs() const;
    void showStone() const;
    // 转换函数(见后文)
    operator int() const;
    operator double() const;
};

#endif
cpp
// weight.cpp
#include <iostream>
#include "weight.h"

Weight::Weight() : stone(0), lbs(0.0) {}

Weight::Weight(double lbsIn)
{
    lbs = lbsIn;
    stone = int(lbs) / LBS_PER_STONE;
}

Weight::Weight(int stn, double lbsIn)
{
    stone = stn;
    lbs = stn * LBS_PER_STONE + lbsIn;
}

void Weight::showLbs() const    { std::cout << lbs << " lbs\n"; }
void Weight::showStone() const  { std::cout << stone << " st\n"; }

Weight::operator int() const    { return int(lbs + 0.5); }
Weight::operator double() const { return lbs; }

隐式转换的发生 ​

因为 Weight(double) 是单参数构造函数,下面这些写法都能工作:

cpp
#include <iostream>
#include "weight.h"

int main()
{
    Weight w = 165.5;     // double 隐式转成 Weight:调用 Weight(double)
    w.showLbs();

    w = 180.0;            // 赋值:先转换成临时 Weight,再赋值
    w.showLbs();
    return 0;
}

Weight w = 165.5; 看起来像把一个 double 赋给 Weight,实际上是编译器发现右边是 double、左边需要 Weight,于是偷偷调用 Weight(double) 构造了一个临时对象。

用 explicit 禁止隐式转换 ​

隐式转换很方便,但也容易出意外——你本想传 Weight 却传了个 double,编译器不报错、悄悄转换,可能埋下 bug。如果想禁止这种"悄悄转换",给构造函数加 explicit:

cpp
class Weight
{
    // ...
    explicit Weight(double lbsIn);   // 不允许隐式转换
};

加了 explicit 后:

cpp
Weight w = 165.5;     // 错误:不能隐式转换
Weight w(165.5);      // OK:直接构造
Weight w2 = Weight(180.0);  // OK:显式转换
w = static_cast<Weight>(170.0);  // OK:显式转换

现代 C++ 建议:单参数构造函数默认加 explicit,除非你确实需要隐式转换。这能避免不少意外。

转换函数:从类转到别的类型 ​

上面还有两个特殊成员函数:operator int() 和 operator double()。它们叫转换函数,定义从本类到其他类型(这里是 int、double)的转换。

特点:

  • 名字是 operator 目标类型,没有返回类型(返回类型已写在名字里)。
  • 通常 const,因为转换不该改对象。
  • 没有参数。

有了它们,Weight 对象能隐式转成 int 或 double:

cpp
#include <iostream>
#include "weight.h"

int main()
{
    Weight w(165.5);
    int pounds = w;         // 调用 operator int()
    double exact = w;       // 调用 operator double()
    std::cout << "四舍五入: " << pounds << "\n";
    std::cout << "精确磅数: " << exact << "\n";
    return 0;
}

转换函数同样可以加 explicit 禁止隐式使用:

cpp
explicit operator int() const;

加了之后 int pounds = w; 会报错,需要写 int pounds = static_cast<int>(w);。C++11 起对转换函数也推荐按需加 explicit。

转换的潜在歧义 ​

如果一个类同时有到 int 和到 double 的转换函数,在需要"数值"的场合编译器可能不知道选哪个,产生二义性:

cpp
Weight w(100.0);
double d = w + 1.0;   // w 转 int 还是 double?可能报"二义性"

解决方法:

  • 用 explicit 限定转换函数,强制显式 static_cast。
  • 或只提供一种转换路径,避免并存。
  • 或调用时显式写 static_cast<double>(w) + 1.0。

转换路径要克制 ​

不要给类堆一堆转换函数。每多一条隐式转换路径,就多一份"编译器悄悄做事"的可能。原则:

  • 需要隐式构造时才不加 explicit,否则加。
  • 转换函数优先 explicit,只在确实需要隐式转(如自定义"数值包装类型")时才开放。
  • 能用一个明确命名的方法(asInt()、toDouble())替代转换函数时,优先用方法——更显式、更安全。

课后练习 ​

  1. 单参数构造:给 Weight 类写一个 Weight(double) 构造函数,在 main 里测试 Weight w = 70.0; 和 w = 80.0; 两种隐式构造/赋值,确认转换发生。
  2. 加 explicit:把上题构造函数加 explicit,重新编译,确认 Weight w = 70.0; 被拒绝、而 Weight w(70.0); 和 static_cast<Weight>(70.0) 仍可用。
  3. 转换函数:给 Duration 类写一个 operator int() 返回总分钟数。测试 int m = someDuration; 能隐式转换。再加 explicit 看效果。
  4. 二义性观察:给某个类同时提供 operator int() 和 operator double(),写 double x = obj + 1.0;,观察编译器是否报二义性错误,然后用 static_cast 解决。