C++ 子类向父类类型转换详解
在C++中,子类向父类进行类型转换是自动进行的。这是因为子类继承了父类的所有成员和方法,所以子类对象可以被视为父类对象。当子类对象被赋值给父类对象时,它会自动进行隐式类型转换。
例如:
class Parent {
public:
void foo() { cout << 'Parent::foo' << endl; }
};
class Child : public Parent {
public:
void bar() { cout << 'Child::bar' << endl; }
};
int main() {
Child child;
Parent parent = child; // 子类对象向父类对象进行类型转换
parent.foo(); // 打印 'Parent::foo'
return 0;
}
在上面的代码中,子类对象child被赋值给了父类对象parent,这个过程中进行了隐式类型转换。父类对象parent只能访问父类的成员和方法,因此调用parent.foo()只会打印出父类的信息。
原文地址: https://www.cveoy.top/t/topic/nsLs 著作权归作者所有。请勿转载和采集!