[問題] 物件繼承與實作的問題 問題在文末
// 程式碼備份: http://nopaste.info/6b4a9226e5.html
// 程式碼備份: http://src.wtgstudio.com/?vw8A8a
#include <iostream>
using namespace std;
template <typename T>
class LineInterface {
private:
public:
typedef LineInterface<T> this_type;
explicit inline LineInterface(void) {}
inline LineInterface(const this_type& d) {}
virtual inline ~LineInterface(void) {}
inline this_type& operator=(const this_type& d) {
if (this != &d) {}
return *this;
}
inline virtual const T& GetX1() const = 0;
inline virtual const T& GetX2() const = 0;
};
template <typename T>
class StartEndLine : public LineInterface<T> {
private:
T m_x1, m_x2;
public:
typedef StartEndLine<T> this_type;
explicit inline StartEndLine(const T& x1 = T(), const T& x2 = T()):
m_x1(x1), m_x2(x2) {}
inline StartEndLine(const this_type& d): m_x1(d.m_x1), m_x2(d.m_x2) {}
virtual inline ~StartEndLine(void) {}
inline this_type& operator=(const this_type& d) {
if (this != &d) {
m_x1 = d.m_x1;
m_x2 = d.m_x2;
}
return *this;
}
inline const T& GetX1() const {
return m_x1;
}
inline const T& GetX2() const {
return m_x2;
}
};
template <typename T>
class StartSameWidthLine : public LineInterface<T> {
private:
static T m_width;
T m_x1;
public:
typedef StartSameWidthLine<T> this_type;
explicit inline StartSameWidthLine(const T& x1 = T()): m_x1(x1) {}
inline StartSameWidthLine(const this_type& d): m_x1(d.m_x1) {}
virtual inline ~StartSameWidthLine(void) {}
inline this_type& operator=(const this_type& d) {
if (this != &d) {
m_x1 = d.m_x1;
}
return *this;
}
inline static void SetWidth(const T& w = T()) {
m_width = w;
}
inline const T& GetX1() const {
return m_x1;
}
inline const T& GetX2() const {
return m_x1 + m_width;
}
};
template<typename T> T StartSameWidthLine<T>::m_width = T();
template <typename T>
inline ostream& operator<<(ostream& os, const LineInterface<T>& d) {
return os << "(" << d.GetX1() << "," << d.GetX2() << ")";
}
int main(int argc, char* argv[]) {
cout << StartEndLine<int>(10, 20) << endl;
StartSameWidthLine<int>::SetWidth(5);
cout << StartSameWidthLine<int>(10) << endl;
system("PAUSE");
return 0;
}
// 程式碼備份: http://nopaste.info/6b4a9226e5.html
// 程式碼備份: http://src.wtgstudio.com/?vw8A8a
錯誤訊息:
.\CPP_AND_C.cpp(xxx) : warning C4172: 傳回區域變數或暫存的位址
.\CPP_AND_C.cpp(xxx) : 編譯類別 樣板 成員函式
'const int &StartSameWidthLine<T>::GetX2(void) const' 時
如果我將
const int &StartSameWidthLine<T>::GetX2(void) const
改成
const int StartSameWidthLine<T>::GetX2(void) const
那麼就違反 沒有完成所有從 LineInterface<T> 繼承而來的Pure virtual function
如果我將
const int &LineInterface<T>::GetX2(void) const
改成
const int LineInterface<T>::GetX2(void) const
那麼就對 StartEndLine<T> 來說這是不必要的複製
請問我該怎麼做呢?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 123.195.88.23
推
04/30 14:03, , 1F
04/30 14:03, 1F
→
04/30 14:04, , 2F
04/30 14:04, 2F
→
04/30 14:23, , 3F
04/30 14:23, 3F
→
04/30 18:20, , 4F
04/30 18:20, 4F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 3 篇):