简体   繁体   English

C ++中的结构初始化错误

[英]struct initialization in c++ error

I'm new to c++, I run the following code in visual studio c++ 我是C ++的新手,我在Visual Studio C ++中运行以下代码

    struct bob
    {
       double a,b;      
       bob(double a,double b);
    }

    int main()
    {
        bob z(2.2,5.6);
        cout<<z.a<<endl;
        keep_window_open();
        return 0;
    }     

when I run this code, i get the following error: 当我运行此代码时,出现以下错误:

Error 1 error LNK2019: unresolved external symbol "public: __thiscall bob::bob(double,double)" (??0bob@@QAE@NN@Z) referenced in function _main C:\\drives\\Comp-Mech\\programming\\VS\\C++\\projects\\E1\\E1.obj E1 错误1错误LNK2019:未解析的外部符号“ public:__thiscall bob :: bob(double,double)”(?? 0bob @@ QAE @ NN @ Z)在函数_main C:\\ drives \\ Comp-Mech \\ programming \\ VS中引用\\ C ++ \\ projects \\ E1 \\ E1.obj E1

您需要实现类bob的构造函数:

 bob::bob(double a,double b) : a(a), b(b) {}

You have provided a declaration for bob 's constructor, but you have not given a definition. 您已经为bob的构造函数提供了声明,但尚未提供定义。 The definition gives the implementation of the constructor and says exactly what it should do. 该定义给出了构造函数的实现,并确切说明了应该做什么。 In this case, you likely want your constructor to assign its arguments to the object's member variables: 在这种情况下,您可能希望构造函数将其参数分配给对象的成员变量:

bob::bob(double a, double b)
{
  this->a = a;
  this->b = b;
}

I used assignment in the above code because you are more likely to be familiar with it. 我在上面的代码中使用了赋值,因为您更可能熟悉它。 However, you should be aware of member initialization lists which allow you to initialize members directly: 但是,您应该知道成员初始化列表,这些列表使您可以直接初始化成员:

bob::bob(double a, double b)
  : a(a), b(b)
{ }

This says to initialise the member a with the argument a and initialise member b with the argument b . 这是说初始化成员a与争论a和初始化成员b的说法b It also avoids potentially expensive default initialization of members before assigning to them. 它还避免了在分配给成员之前潜在的昂贵的成员默认初始化。

That's because you haven't written the code for bob::bob(double, double) . 这是因为您尚未编写bob::bob(double, double)

struct bob
{
   double a,b;      
   bob(double aa, double bb) a(aa), b(bb) {}
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM