开发者

C++ problem in declaring a struct

I am unable to see what is wrong in the following (very contrived) code. It might be the way I have declared a size 2 vector inside the mystruct. But isn't that how we declare a vector of size 2 whose contents we have yet to initialize?

struct mystruct
{
  int a;
  int b;
  vector<double> c(2);    };

   int main(int argc, char *argv[])
{
  mystruct test;
  (test.c)[0]=3.4;
  (test.c)[1]=1.8;
  return 0;    }

The compiler is throwing me the following error message:

g++ 开发者_如何学编程-Wall simple.cpp

simple.cpp:18: error: expected identifier before numeric constant

simple.cpp:18: error: expected ‘,’ or ‘...’ before numeric constant

simple.cpp: In function ‘int main(int, char**)’:

simple.cpp:32: error: invalid types ‘[int]’ for array subscript

simple.cpp:33: error: invalid types ‘[int]’ for array subscript


You cannot initialize mystruct::c in the class definition, this has to be done in the constructor.

struct mystruct {
  mystruct() : c(2) { }
  vector<double> c;
};


You're trying to construct c in your struct declaration. Vectors only have a size upon construction. Try:

struct mystruct {
    mystruct(): c(2) {}
    int a;
    int b;
    vector<double> c;
};

The mystruct() constructor uses the member initialisation syntax c(2) to construct c.


You need a constructor if you want to initialize the vector (call vector's constructor)

struct mystruct
{
  int a;
  int b;
  vector<double> c;

  mystruct():
    c(2)
    {

    }
};


That's just not how C++ works.

When you declare a class, you cannot specify constructors for member objects (with the exception of static constant integrals). Instead, you must specify the constructor arguments for members in the class's constructor initializer list:

class Foo
{
  std::vector<int> v;
public:
  Foo() : v(2) { }
};


This isn't a valid declaration:

vector<double> c(2);

You probably want:

vector<double> c;

Then, in main:

int main(int argc, char *argv[])
{
     mystruct test;
     test.c.push_back(3.4);
     test.c.push_back(1.8);
     return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜