2016-12-26 36 views
-1

給下面的程序,C++調用模板的構造方法實例

hello.h

#ifndef HELLO_ 
#define HELLO_ 

template <typename T> 
class hello 
{ 
    T _data; 
public: 
    hello(T t) 
    : _data(t) {} 
}; 

template <typename T> 
class world : public hello<T> 
{ 
    T _data; 
public: 
    world(T t) 
    : hello<T>(t) {} 
}; 

#endif 

main.cc

#include <iostream> 
#include "hello.h" 

using namespace std; 

class Foo 
{ 
    int _x; 
public: 
    Foo(int x) : _x(x) {} 
}; 

int main() 
{ 
    Foo f(1); 
    world<Foo> w(f); 

    return 0; 
} 

我編譯它C++ 11和編譯器給出了以下錯誤消息:

In file included from main.cc:2:0: 
hello.h: In instantiation of ‘world<T>::world(T) [with T = Foo]’: 
main.cc:16:22: required from here 
hello.h:19:15: error: no matching function for call to ‘Foo::Foo()’ 
    : hello<T>(t) {} 
      ^
main.cc:10:3: note: candidate: Foo::Foo(int) 
    Foo(int x) : _x(x) {} 
^
main.cc:10:3: note: candidate expects 1 argument, 0 provided 
main.cc:6:7: note: candidate: constexpr Foo::Foo(const Foo&) 
class Foo 
    ^
main.cc:6:7: note: candidate expects 1 argument, 0 provided 
main.cc:6:7: note: candidate: constexpr Foo::Foo(Foo&&) 
main.cc:6:7: note: candidate expects 1 argument, 0 provided 

必須有我在模板定義中錯過的東西,但我不確定它在哪裏。對於原始類型,如intdouble,它可以工作。它不適用於我定義的類,例如Foo

+0

world w(f); – user1438832

+0

@ user1438832'world w();'是非常有效的C++代碼 – Danh

+0

對不起,是它的有效,但目的是傳遞foo對象。 – user1438832

回答

2

world<T>

template <typename T> 
class world : public hello<T> 
{ 
    T _data; 
public: 
    world(T t) 
    : hello<T>(t) {} 
}; 

由於T在這種情況下(Foo)不是默認-構造的。我想這是錯誤的補充,因爲在hello<T>有另一個T _data;。刪除它,你的代碼應該運行良好。就像這樣:

template <typename T> 
class world : public hello<T> 
{ 
public: 
    world(T t) 
    : hello<T>(t) {} 
}; 

Demo


不關你問的錯誤,在你的主:

world<Foo> w(); 

這聲明w爲不帶參數的函數,返回world<Foo>

我想這不是你想要的(原諒我,如果我錯了)。我想這是你想要什麼:

world<Foo> w(f); 

world<Foo> w{f}; 
0

父類的私有數據進行封裝,它們確實存在。在子類中重複定義具有相同變量名稱的數據會引發此類錯誤,無論它是關於模板類還是普通類。