C ++ struct构造函数 [英] C++ struct constructor

查看:931
本文介绍了C ++ struct构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建自己的结构。所以我写了这段代码。

  struct node 
{
int val,id;
node(int init_val,int init_id)
{
val = init_val;
id = init_id;
}
};

node t [100];

int main()
{
...
}

我试图编译我的程序。但我有一个错误:

 错误:没有匹配的函数调用'node :: node()'
注意:候选者是:
note:node :: node(int,int)
注意:候选者期望有2个参数,0提供
note:node :: node(const node&)
note:candidate expects 1 argument,0 provided


解决方案

$ p> node t [100];

将尝试通过调用节点的默认构造函数来初始化数组。您可以提供默认构造函数

  node()
{
val = 0;
id = 0;
}

或相当冗长,明确地初始化所有100个元素

 节点t [100] = {{0,0},{2,5},...} //为100个元素重复

或者,因为您使用的是C ++,请使用

$ p

<$ p>

p $ p> std :: vector< node> t;


I tried to create my own structure. So I wrote this piece of code.

struct node
{
    int val, id;
    node(int init_val, int init_id)
    {
        val = init_val;
        id = init_id;
    }
};

node t[100];

int main()
{
...
}

I tried to compile my program. But I got an error:

error: no matching function for call to 'node::node()'
note: candidates are:
note: node::node(int, int)
note: candidate expects 2 arguments, 0 provided
note: node::node(const node&)
note: candidate expects 1 argument, 0 provided

解决方案

node t[100];

will try to initialise the array by calling a default constructor for node. You could either provide a default constructor

node()
{
    val = 0;
    id = 0;
}

or, rather verbosely, initialise all 100 elements explicitly

node t[100] = {{0,0}, {2,5}, ...}; // repeat for 100 elements

or, since you're using C++, use std::vector instead, appending to it (using push_back) at runtime

std::vector<node> t;

这篇关于C ++ struct构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆