简体   繁体   中英

Passing parameter to a constructor

I created a class vector in C++ and then tried to use an vector object in a different class called abc .

What I want to do is define a object in class abc of type vector

Something like this:

#include <iostream>
using namespace std;


class vector{
public:
    double icomponent=1;
    double jcomponent=1;
    double kcomponent=1;

    vector(double conI, double conJ, double conK){   //constructor
         icomponent = conI;
         jcomponent = conJ;
         kcomponent = conK;
    }
};

class abc{
    double i,j,k;
    vector velocity(i,j,k); 
};

However this code doesn't compile and throws this error:

member "abc::i" is not a type name

I don't understand what is causing the problem. Can anyone figure it out?

I tried searching online, but the closest I could find is- this , but that one was caused by some header file reference issues, and not related to this one.

You cannot do what you are trying to do in the way you've defined. Essentially, you cannot pass the variables i , j , and k to the constructor for velocity in such a manner. You need a constructor. Example:

class abc {
    double i, j, k;
    vector velocity;
public:
    abc( double i, double j, double k ) : i{i}, j{j}, k{k}, velocity{ i, j, k } {}
};

This uses the member initializer list to initialize the three double variables, as well as the velocity variable.

Alternatively, as user17732522 mentions in the comments below, if your variables are public, you can do what you were trying with a slight modification:

class abc {
public:
    double i, j, k;
    vector velocity = vector{ i, j, k };
};

In order to use this method, you must initialize the i , j and k during construction of the object (either through a constructor, or through an aggregate initialization as shown below), otherwise, you will get undefined behaviour by utilizing uninitialized variables in the creation of the velocity object.

int main()
{
    abc a{ 1, 2, 3 };
    std::cout << a.velocity.icomponent << '\n'; // print 1
    std::cout << a.velocity.jcomponent << '\n'; // print 2
    std::cout << a.velocity.kcomponent << '\n'; // print 3
}

The problem with vector velocity( i, j, k ); that you were trying, is that the C++ compiler interprets this as a function called velocity which returns a vector , then i , j and k are expected to be types (which of course they are not).

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