o****b 发帖数: 31 | 1 #include
class example{
public:
static const int vecSize=20;
std::vectorvec(vecSize);
};
this is in h file
const int example::vecSize;
this is in cpp file
为什么编译不过?我认为既然vecSize已经是const int了,就应该可以初始化vec呀。
那位大侠解释
一下,谢了。 |
c**********e 发帖数: 2007 | 2 Are you declaring vecSize the 2nd time? |
o****b 发帖数: 31 | 3 const static member is initialized in class, but must still be defined
outside the class definition. |
S*********g 发帖数: 5298 | 4 what is the variable vecSize in your constructor?
【在 o****b 的大作中提到】 : const static member is initialized in class, but must still be defined : outside the class definition.
|
o****b 发帖数: 31 | 5 vecSize is defined as static const int=20 in the class.
【在 S*********g 的大作中提到】 : what is the variable vecSize in your constructor?
|
m*******r 发帖数: 98 | 6 One problem: std::vector vec(vecSize)
this is a definition, not a declaration.
One bad use: const int example::vecSize
as long as you don't take the address of vecSize, there is no need to define
it again outside the class.
//example.h
#include
class example{
public:
example():vec(vecSize){}
static const int vecSize = 20;
private:
std::vector vec;
};
【在 o****b 的大作中提到】 : #include : class example{ : public: : static const int vecSize=20; : std::vectorvec(vecSize); : }; : this is in h file : const int example::vecSize; : this is in cpp file : 为什么编译不过?我认为既然vecSize已经是const int了,就应该可以初始化vec呀。
|
m*******r 发帖数: 98 | 7 他那个不是constructor
【在 S*********g 的大作中提到】 : what is the variable vecSize in your constructor?
|
o****b 发帖数: 31 | 8 One problem: std::vector vec(vecSize)
能不能讲讲这里,不太懂。还有为什么如果我把vector换成array就可以,如下
class example{
public:
static const int vecSize = 20;
double arr[vecSize];
};
谢谢了
define |
m*******r 发帖数: 98 | 9 the type of vec is vector
the type of arr is double [vecSize]
【在 o****b 的大作中提到】 : One problem: std::vector vec(vecSize) : 能不能讲讲这里,不太懂。还有为什么如果我把vector换成array就可以,如下 : class example{ : public: : : static const int vecSize = 20; : double arr[vecSize]; : }; : 谢谢了 : define
|
c*****o 发帖数: 178 | 10 在cpp中不要再定义了。很奇怪,c++primer中说必须要在体外定义,但是就是不能通过
,link错误,说重复定义。我也觉得很奇怪,等高人解答。面试问我这个,可咋说呢?
我用的是visual studio2008
【: One problem: std::vector vec(vecSize) |
h*****0 发帖数: 4889 | 11 你如果要define的话,为啥没给一个值?
【在 o****b 的大作中提到】 : const static member is initialized in class, but must still be defined : outside the class definition.
|
m*******r 发帖数: 98 | 12 see effective c++ item 2
【在 h*****0 的大作中提到】 : 你如果要define的话,为啥没给一个值?
|
K*****n 发帖数: 65 | 13 members can not be initialized in class DEFINITION.They need to be
initialized via constructor.
Instead of
class CTest
{
public:
CTest(){};
private:
int nX(0);
};
You will need
class CTest
{
public:
CTest:nX(0){};
private:
int nX(0);
};
When you change vector to array, then it is OK because array
is declaration.To achieve what you intended:
class example{
public:
static const int vecSize = 10;
example(){vec.resize(vecSize);};
std::vector vec; |
o****b 发帖数: 31 | |