简体   繁体   English

将向量传递给类的构造函数

[英]Passing a vector to constructor of a class

Note : I have seen all the similar questions on this website, but I still could not make this work.注意:我已经在这个网站上看到了所有类似的问题,但我仍然无法完成这项工作。

I made a class for astronomical coordinates and I am trying to overload the << operator to store user input in the class.我为天文坐标创建了一个类,我试图重载 << 运算符以将用户输入存储在类中。 The two coordinates (right ascension and declination) are vectors of doubles.两个坐标(赤经和赤纬)是双精度矢量。

When I call the parametrised constructor, I get the following two errors: "call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type" and "no match for call to '(coordinates) (std::vector&, std::vector&)'".当我调用参数化构造函数时,出现以下两个错误:“调用没有适当的 operator() 或转换函数到函数指针类型的类类型的对象”和“不匹配调用 '(坐标) (std::vector&, std::vector&)'"。 It seems like I have to pass the vectors by reference, but I haven't managed to.似乎我必须通过引用传递向量,但我没有设法。 How do I make it work?我如何使它工作?

Here is the code:这是代码:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

class coordinates {
protected: 
    std::vector<double> right_ascension, declination; 
public:
    std::vector<double> zero_vector{(1,0)};
    coordinates(): right_ascension{zero_vector}, declination{zero_vector} {} // Default constructor
    coordinates(std::vector<double> ra, std::vector<double> dec) : right_ascension{ra}, declination{dec} {} // Paramterised constructor
    ~coordinates(){std::cout << "Calling coordinates destructor" << std::endl;}

    friend std::istream& operator>>(std::istream &is, coordinates &coords);
};

std::istream& operator>>(std::istream &is, coordinates &coord){    
    // Read imput from string stream "1.1 2.2 3.3; 4.4 5.5 6.6"
    std::string right_ascension;
    double hh, mm, sec;
    std::vector<double> ra, dec;
    
    // Read data
    std::stringstream ss("");
    std::getline(is, right_ascension, ';');
    ss.str("");
    ss << right_ascension; 
    ss >> hh >> mm >> sec;
    ra.push_back(hh);
    ra.push_back(mm);
    ra.push_back(sec);

    is >> hh >> mm >> sec;
    dec.push_back(hh);
    dec.push_back(mm);
    dec.push_back(sec);
    
    coord(ra, dec); // Here I get the two errors I mentioned
    return is;
}

int main() {
    coordinates coords;
    std::cout << "Input numbers (hh mm ss; hh ss mm)";
    std::cin >> coords;
    return 0;
}

The correct syntax to create an object is:创建对象的正确语法是:

coord = coordinates(ra, dec);

or或者

coord = coordinates{ra, dec};

(depending on your preferred style). (取决于您喜欢的风格)。 This code constructs an object of type coordinates and then assigns it to the coord parameter.此代码构造一个coordinates类型的对象,然后将其分配给coord参数。

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

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