用基类指针调用基类的值构造函数的语法是通过基类指针进行间接调用。具体步骤如下:
示例代码如下:
#include <iostream>
class Base {
public:
int value;
Base(int val) : value(val) {
std::cout << "Base constructor called." << std::endl;
}
};
class Derived : public Base {
public:
Derived(int val) : Base(val) {
std::cout << "Derived constructor called." << std::endl;
}
};
int main() {
Derived derivedObj(10);
Base* basePtr = &derivedObj;
basePtr->Base::Base(20); // 通过基类指针调用基类的值构造函数
std::cout << "Value: " << basePtr->value << std::endl;
return 0;
}
输出结果:
Base constructor called.
Derived constructor called.
Base constructor called.
Value: 20
在上述示例中,通过派生类对象创建了一个基类指针basePtr
,然后使用basePtr->Base::Base(20)
语法调用了基类的值构造函数,最后输出了基类对象的value
值。
领取专属 10元无门槛券
手把手带您无忧上云