簡體   English   中英

類型轉換重載

[英]Typecast overloading

我可以重載'+'運算符,但不確定如何為NewType進行類型轉換。 我希望將其轉換為其他任何變量類型。 您能提供一些建議嗎? 非常感謝!

#include <iostream>

class NewType {
private:
  float val;

public:
  NewType(float v) { val = v; }
  friend NewType operator+(const NewType &c1, const NewType &c2);
  float GetVal() const { return val; }
};

NewType operator+(const NewType &c1, const NewType &c2) { return NewType(c1.val + c2.val); }

int main() {
  NewType a = 13.7;
  // Here is the problem, I would like this to print 13.
  std::cout << (int) a << std::endl;
  return 0;
}

我希望將其轉換為其他任何變量類型。

對於任何其他變量類型,您需要模板化的用戶定義轉換:

class NewType {
public
// ...
   template<typename T>
   explicit operator T() const { return T(val); } 
// ...
};

explicit (此處為C ++ 11及更高版本)可確保您將使用顯式強制轉換,即:

NewType a = 13.7;
int n = a; // compile error
int n2 = static_cast<int>(a); // now OK

您還可以在用戶定義的轉換運算符中使用統一初始化:

   template<typename T>
   explicit operator T() const { return T{val}; } 

如果您的演員表可能需要縮小,這將給您額外的警告。 但是,正如我在gcc下看到的那樣,默認情況下僅生成警告(我記得這是設計使然-由於許多舊代碼會中斷),在clang下會生成錯誤:

main.cpp:15:16: error: type 'float' cannot be narrowed to 'int' in initializer list [-Wc++11-narrowing]
      return T{val}; 

並且相同的Visual Studio會產生錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM