search

Home  >  Q&A  >  body text

c++ - 为什么这样写是错误的??

为什么这样写的话,编译器会提示vecsize is not a type

#include <iostream>
#include <vector>
struct A
{
    static const int vecSize = 20;
    static std::vector<double> vec(vecSize);
};

但如果改成这样就没问题

#include <iostream>
#include <vector>
struct A
{
    static const int vecSize = 20;
    static std::vector<double> vec;
};
std::vector<double> A::vec(vecSize);
高洛峰高洛峰2803 days ago546

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 13:52:36

    Because

    std::vector<double> vec(vecSize);
    

    is regarded as a function signature, and the return value is std::vector<double>, so an error occurs when parsing vecSize.
    In addition, static non-literal type members in a class need to be initialized outside the class, which is stipulated by C++.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 13:52:36

    The process of constructing the object type member variable vec must be in the constructor and cannot be constructed when it is declared.

    reply
    0
  • Cancelreply