使用派生类"istream"读取基类的属性
Read an attribute of the base class using "istream" of derived class
看起来Coord(a)
不起作用,并且lon
和lat
的值是00.0000
和00.0000
的,来自默认构造函数的值。我该怎么办?语法有问题吗?从基类读取lon
和lat
不是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>>
.
相关文章:
- 基类需要派生类属性
- 使用基类的C++和修改私有/受保护的属性
- 子类中具有不同值的静态基类属性
- 即使基类属性在完成向下转换时是虚拟的,是否有效
- 继承:派生类的基类属性可访问性
- 通过"a pointer of the base class"访问未在基类中声明的子类的方法或属性(动态)
- 基类如何知道其派生类的属性
- C++基类指针容器中,编辑特定对象的属性
- C++引用基类中的子类指针属性
- C++派生类的设置属性到从同一基类派生的未知类对象
- C++:新的基类,但它可以访问派生类的属性
- C++-填充派生类数据成员,同时设置基类属性值
- C++ 修改基类的属性
- 从基类指针比较模板化子类的属性
- 是否可以在初始化列表中使用基类属性
- 如何在C++中从基类访问派生类的属性
- 基类作为属性
- 使用派生类"istream"读取基类的属性
- 实现基类方法来访问派生类的属性
- 基类属性的不同初始化