简体   繁体   中英

C++ Parametrized Constructor Error

I'm writing a code for creating a simple C++ class using a parametrized constructor. My code is as follows:

#include <iostream>
using namespace std;

    class CC{
    public:
      double h[];
      double t[];
      int tsize;

      CC(double rs[], double ts[], int l){
        for (int k = 0;k < l;k++){
         t[k] = ts[k];
         h[k] = rs[k];
         };
        tsize = l;
      };
    };

    int main(int argc, char const *argv[])
    {
        double r[] = {1,4,9};
        double tm[] = {1,2,3};
        int s = 3;
        CC CC1(r,tm,s);
        cout<<CC1.h[0]<<CC1.h[1]<<CC1.h[2]<<endl;
        cout<<CC1.t[0]<<CC1.t[1]<<CC1.t[2]<<endl;
    };

It gives me output as :

149
149

whereas it should have been

149
123

Can anybody please tell me what wrong am I doing here?

In the class definition, double h[]; is an error. You must specify the bounds of the array as part of the class definition, for example:

double h[5];

and then in your constructor check that you didn't receive l > 5 . (BTW don't use l as a variable name, it looks too much like 1 ). Your compiler should have given an error about this.

If you don't know at compile-time how big to make your array, then you cannot use a C-style array. Instead use a C++-style array; those are called vectors:

vector<double> h, t;

Since vectors can be initialized by passing a pair of pointers which bound the initial data, you can write your constructor like this:

CC(double rs[], double ts[], int length)
    : h(rs, rs+length), t(ts, ts+length), tsize(length) 
{ }

Bonus: it's possible to deduce the length from the arrays you pass in , if you are passing actual arrays (not pointers):

template<size_t length>
CC(double (&rs)[length], double (&ts)[length])
    : h(rs, rs+length), t(ts, ts+length), tsize(length)
{ }

Usage:

CC cc1(r, tm);

You could have this constructor instead of or in addition to the other constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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