使用派生类"istream"读取基类的属性

Read an attribute of the base class using "istream" of derived class

本文关键字:基类 属性 读取 istream 派生      更新时间:2023-10-16

看起来Coord(a)不起作用,并且lonlat的值是00.000000.0000的,来自默认构造函数的值。我该怎么办?语法有问题吗?从基类读取lonlat不是in >> Coord(a)吗?

 //base class
class Coord {
    private:
    double lon;
    double lat;
Coord() { lon = 00.000000000000000; lat = 00.000000000000000; }
//.....
//.....
//.....
friend istream& operator>>(istream& in, Coord& temp)
{
    cout << "Longitude is : "; in >> temp.lon;
    cout << "Latitude is  : "; in >> temp.lat;
    return in;
}
};
//derived class   
class Location : public Coord {
private:
    char model[6];
    double time;
    int speed;
//.....
//.....
//.....
friend istream& operator>>(istream& in, Location& a)
{
    cout << "Model is : "; in >> a.model;
    cout << "Time is : "; in >> a.time;
    cout << "Speed is : "; in >> a.speed;
    cout << "Coordinates : " << endl; in >> Coord(a);
    return in;
}
};
void main()
{
   Location loc;
   cin>>loc; cout<<loc;
}

正如我所说,Coord(a)创建一个副本(很像对象切片)。你的代码不应该编译,因为你正在将右值传递给operator>>,它需要一个左值引用。

您必须使用 static_cast 来获取对Coord基类的引用

in >> static_cast<Coord&>(a);

这将使它被称为正确的operator>> .