第854页的"The C++ Programming Language Third Edition"中的代码是否正确?

ABE*_*rov 13 c++

我尝试学习C++.在"The C++ Programming Language Third Edition"一书中,我找到了第854页的代码(附录C.13.1):

template<class T> class X {
    static T def_val;
    static T* new_X(T a = def_val);
};

template<class T> T X<T>::def_val(0, 0);
template<class T> T* X<T>::new_X(T a) { /* ... */ }

template<> int X<int>::def_val<int> = 0;
template<> int* X<int>::new_X<int>(int i) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

我修改它:

template<class T> class X {
    static T def_val;
    static T* new_X(T a = def_val);
};

template<class T> T X<T>::def_val(0, 0);
template<class T> T* X<T>::new_X(T a) { return new T(a); }

template<> int X<int>::def_val<int> = 0;
template<> int* X<int>::new_X<int>(int i) { return new int(i); }
Run Code Online (Sandbox Code Playgroud)

但我的编译器不会编译它:

1>main.cpp(15): error C2143: syntax error : missing ';' before '<'
1>main.cpp(15): error C2988: unrecognizable template declaration/definition
1>main.cpp(15): error C2059: syntax error : '<'
1>main.cpp(16): error C2143: syntax error : missing ';' before '<'
1>main.cpp(16): error C2470: 'X<T>::new_X' : looks like a function definition, but there is no parameter list; skipping apparent body
1>          with
1>          [
1>              T=int
1>          ]
1>main.cpp(16): error C2988: unrecognizable template declaration/definition
1>main.cpp(16): error C2059: syntax error : '<'
1>main.cpp(19): error C2143: syntax error : missing ';' before '{'
1>main.cpp(19): error C2447: '{' : missing function header (old-style formal list?)
1>
1>Build FAILED.
Run Code Online (Sandbox Code Playgroud)

书或编译器中的代码有什么错误?

Jol*_*hic 17

这本书的代码是错误的.最后两行应为:

template<> int X<int>::def_val = 0;
template<> int* X<int>::new_X(int i) { return new int(i); }
Run Code Online (Sandbox Code Playgroud)


Mac*_*ser 13

别忘了邮寄Stroustrup.从他的主页:

"由于我的感激之情的小礼物的人谁汇报的问题,从而帮助我提高的书,我提供了一个奖励的人谁首先报道了拼写错误,在代码示例中的错误,或在文本给我一个事实错误.文本中新错误的赏金是32美元."

编辑:哎呀.你太迟了.这个错误在第19次印刷中得到了修复.看到这里.所以没有赏金,对不起!

更正后的版本如下所示:

template class X {
    // ...
    static T def_val;
    static T* new_X(T a = def_val);
};

template< class T> T X<T>::def_val; // initialize to X<T>()
template< class T> T* X<T>::new_X(T a) { /* ... */ }

template< > int X<int>::def_val = 0;
template< > int* X<int>::new_X(int i) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)