0

テンプレートの外部でメンバー関数を宣言しようとしています - GetValue。

エラーが発生しています: main.cpp|16|エラー: 'GenericType Test::GetValue()'| の再定義| |エラー: 'GenericType Test::GetValue()' は以前ここで宣言されました|

#include <iostream>

template <class GenericType>
class Test {
public:
        GenericType x;
        Test(){        }

        Test(int y) : x(  y){ }

        GenericType GetValue(){}
};


template <class GenericType>
GenericType Test<GenericType>::GetValue(){
    return x;

}

int main()
{

    Test<int> y(5);
    std::cout << y.GetValue();
    return 0;
}
4

4 に答える 4

2

クラス宣言では、すでにGetValue()メソッドを定義しています。

ただ行う:

template <class GenericType>
class Test {
public:
     // ...

     GenericType GetValue();
     //                    ^
};
于 2013-09-18T15:02:47.203 に答える
1

さて、コード内の関数を 2 つのポイントで定義しています。

template <class GenericType>
class Test {
public:
        GenericType x;
        Test(){        }

        Test(int y) : x(  y){ }

        GenericType GetValue(){} //<--here
};


template <class GenericType>
GenericType Test<GenericType>::GetValue(){ // <- and Here!
    return x;

}

int main()
{

    Test<int> y(5);
    std::cout << y.GetValue();
    return 0;
}

最初の定義は宣言でなければなりません。{} を ; に変更してください。

GenericType GetValue();

ここで、この関数はコードの後半で定義されると言っています

于 2013-09-18T15:04:58.917 に答える