如何在C ++中使用for循环创建多个对象? [英] How can I create multiple objects with for loop in C++?

查看:65
本文介绍了如何在C ++中使用for循环创建多个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用for循环创建多个对象,因为最终我将希望该程序根据我的输入创建不同数量的类.我试图使用对先前问题的答案来编写此代码.但是,当我尝试编译时,出现错误没有匹配的函数来调用'Genes :: Genes()'

I am trying to create multiple objects using a for loop, as eventually I will want this program to create different numbers of the class depending on my input. I tried to write this using an answer to a previous question. However, when I try to compile I get the error 'no matching function for call to 'Genes::Genes()'

#include <iostream>
#include <cstdlib>
#include <ctime> 

using namespace std;

float random();

class Genes{
 public:
 double cis;
 double coding;
 double effect;
 Genes(double a, double b, double c);
};

Genes::Genes(double a, double b, double c) 
{
  cis=a;
  coding=b;
  effect=c;
};

int main()
{
  int geneno, i;

  srand(time(NULL));

  geneno=4; //this will probably be cin later

  Genes *genes=new Genes[10]

  for(i=0;i<=geneno;i++){
    double d,e,f;

    d=random();
    e=random();
    f=random();

    genes[i]=Genes(d,e,f);

    cout<<"cis is "<<genes.cis<<'\n';
    cout<<"coding is "<<genes.coding<<'\n';
    cout<<"Effect for gene is "<<genes.effect<<'\n';

    }
 delete[] genes;
 }


float random(){

  float decRANDMAX;

 decRANDMAX=RAND_MAX*1.0;

 return rand()%(RAND_MAX+1)/decRANDMAX;

}  

推荐答案

在C ++中,使用new []创建数组会使用其默认/无参数构造函数初始化所有对象.

In C++, creating an array with new[] initializes all the objects with their default/no-parameter constructor.

所以这行:(添加了分号)

So this line: (semicolon added)

 Genes *genes=new Genes[10];

将导致对Genes :: Genes()的十次调用.

Will result in ten calls to Genes::Genes().

这通常看起来不错,因为当您不声明任何C ++时,C ++将为您提供默认的构造函数.但是,要做到这一点,您一定不能声明任何构造函数.您的构造函数:

That would normally seem fine, since C++ will give you a default constructor when you don't declare any. However, for this to happen, you must not declare any constructors. Your constructor:

Genes::Genes(double a, double b, double c)

防止编译器为您创建默认的构造函数,从而阻止您制作Genes对象数组.

Prevents the compiler from creating a default constructor for you, which in turn prevents you from making an array of Genes objects.

对此问题有两种合理的解决方案:

There are two reasonable solutions to this problem:

  1. 您可以向Genes类添加默认/无参数构造函数.这很简单,但缺乏优雅.什么是默认的Genes对象?如果这样的对象有意义,则您可能已经声明了默认构造函数.

  1. You could add a default/no argument constructor to the Genes class. This is simple, but lacks some elegance. What is a default Genes object? If such an object made sense, you probably would have declared a default constructor already.

使用std :: vector代替数组: http://www.cplusplus.com/reference/stl/vector/.从短期来看,这是一个较复杂的修复程序,但从长远来看,熟悉标准模板库(提供向量类)将很有价值.就是说,如果您只是在学习C ++并且以前没有看过模板,那么这可能有点让人不知所措,并且您可能想先阅读一些有关模板的知识.(例如,在 http://www.learncpp.com/cpp-tutorial/143-template-classes/)

Look into using std::vector instead of an array: http://www.cplusplus.com/reference/stl/vector/ . While this is a more complicated fix in the short term, being familiar with the Standard Template Library (which supplies the vector class) will be valuable in the long term. That said, if you are just learning C++ and haven't seen templates before, this might be a bit overwhelming and you might want to read a bit about templates first. (for example, at http://www.learncpp.com/cpp-tutorial/143-template-classes/ )

vector类允许您声明容量,即要放入数组中的对象数量(或者您可能不声明容量,从而导致插入速度较慢).然后,它将仅在将对象放入向量中时构造对象.您的代码如下所示:

The vector class allows you to declare a capacity, for how many objects you will put into your array (or you may not declare a capacity, resulting in a slower insert). Then, it will only construct objects when they are placed into the vector. Your code would look something like this:

#include <vector> // to get the vector class definition
using std::vector; // to 

vector<Genes> genes;
genes.reserve(geneno); // optional, but speeds things up a bit

for(i = 0; i <= geneno; i++) {
    double d = random();
    double e = random();
    double f = random();

    genes.push_back(Genes(d, e, f));
}

最后一条语句(大致)等同于:

The last statement is (roughly) equivalent to:

Genes temp(d, e, f);
genes.push_back(temp);

vector :: push_back在矢量的后面添加一个项目,并将矢量容量增加1: http://www.cplusplus.com/reference/stl/vector/push_back/

vector::push_back adds an item to the back of the vector and increases the vector capacity by 1: http://www.cplusplus.com/reference/stl/vector/push_back/

您可以随后以与数组相同的方式访问向量中的元素:

You can subsequently access elements in the vector the same way as you would the array:

cout << "The third gene's coding is " << genes[3].coding << endl;

您可以使用vector :: size():

And you can query the size of the vector with vector::size():

cout << "The vector has " << genes.size() << "elements" << endl;

这篇关于如何在C ++中使用for循环创建多个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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