2011-10-18 26 views
1

在將用於數值計算大量數據的代碼中,C++中向上轉換的原因是什麼(我正在使用的庫)?爲什麼使用算術和訪問操作符時的upcast

考慮以下層次:

template<class T> 
class unallocatedArray 
{ 
    public: 
     unallocatedArray(int size, T t) 
      : size_(size), t_(0) 
     { 

     } 

     // Copy constructor. This is the only way to 
     // actually allocate data: if the array is 
     // passed as an argument to the copy constr. 
     // together with the size. 

     // Checks. Access operators. Iterators, etc. 
     // Wrappers for stl sorts... 

    private: 
     int size_; 
     T* t_; 
}; 


template<class T> 
class myArray 
: public unallocatedArray<T> 
{ 
    public: 
     // This type actually allocates the memory. 
     myArray (int size) 
      : unallocatedArray<T>(size) 
     { 
      // Check if size < 0.. 

      // Allocate. 
      this->t_ = new T[size]; 
     } 

     myArray (int size, T t) 
     { 
      this->t_ = new T[size]; 

      for (int i = 0; i < this->size_; i ++) 
      { 
       this->t_[i] = t; 
      } 
     } 

     // Some additional stuff such as bound checking and error handling. 
     // Append another array (resizing and memory copies), equality 
     // operators, stream operators, etc... 

}; 

template<class T> 
class myField 
: public myArray<T> 
{ 
    public: 
     // Constructors call the parent ones. No special attributes added. 

     // Maping operations, arithmetical operators, access operator. 
}; 

// 

template<class T> 
class geomField 
: public myField<T> 
{ 
    // myField but mapped on some kind of geometry, like surface meshes, 
    // volume meshes, etc. 
}; 

這只是一個非常非常簡單的模型,只是聲明,訪問操作員了定義所有的方式,和算術運算符放在MyField的類。現在,會是什麼原因上溯造型geomField到MyField的,如果需要執行說1e07倍以下:

GeomField<myType> geomFieldObject; 

myField<myType>& downCast = geomFieldObject; 

// Do the arithmetical operations on the downCast reference. 

訪問元素 按以下方式進行算術表達式

兩個這樣的領域?是不是也引入了某種懲罰?算術運算符是否不公開給geomField?這不是公共繼承的全部要點嗎?

我沒有設計這一點,這是從我參與開發的OS庫。:)

謝謝!

+1

沮喪的地方在哪裏?我們沒有看到它。 C++有很多具有非常不同特徵的演員操作符。我們無法從這段代碼中看出來。 – sehe

+4

a)這只是一個窮人的'矢量'? b)你在談論什麼是「接入運營商」? c)你的意思是「upcast」,d)沒有什麼是虛擬的,所以沒有運行時調度。 –

+0

是的,它是一個窮人的載體,它是在STL之前開發的。 b)運營商[]將是接入運營商 - 這個窮人的包裝,c)upcast ...對不起。d)這意味着什麼? (我是一名機械工程師) – tmaric

回答

1

我只能猜測,但一些算術操作可能已被覆蓋在geomField爲了實現幾何映射。

如果您有geomField中的數據但想要執行未映射的操作,那可能是上傳的原因。

另一方面,如果在鑄造參考上執行的操作中沒有一個在geomField上被覆蓋,那麼您是對的,不需要進行鑄造。

而且通常情況下,上傳不會引入任何性能缺陷,因爲通常(或者甚至在任何情況下,我現在都不確定......)完全在編譯時完成:考慮以下類:

class A { 
public: 
    void f(); 
}; 

class B : public A { 
public: 
    void f(); // Overwrites A::f 
}; 

當你的代碼看起來像

B obj; 
obj.f(); 

它是由編譯器像

B::f(&obj); 
翻譯所

static_cast<A>(obj).f(); 

導致

A::f(&obj); 

即有通過澆鑄引入沒有運行時開銷。

相關問題