您的代码中缺少一些头文件的引用,包括iostream和string。此外,在printInfo函数中,需要在输出语句的末尾添加一个结束符号。下面是修改后的代码:
#include <iostream>
#include <string>
/* 基类 --------------------------------------------------------------------*/
class Company
{
public:
Company(std::string theName);
virtual void printInfo(void); //基类也需要加virtual
protected:
std::string name;
};
/* 子类 --------------------------------------------------------------------*/
class TechCompany : public Company //class xxx : public xxx
{
public:
TechCompany(std::string theName, std::string theProduct);
virtual void printInfo(void);
private:
std::string product;
};
/* 函数 --------------------------------------------------------------------*/
//Company
Company::Company(std::string theName)
{
name = theName;
}
void Company::printInfo(void)
{
std::cout << "Company name: " << name << std::endl;
}
//TechCompany
TechCompany::TechCompany(std::string theName, std::string theProduct) : Company(theName)
{
product = theProduct;
}
void TechCompany::printInfo(void)
{
std::cout << "Company name: " << name << std::endl;
std::cout << "Product: " << product << std::endl;
}
int main()
{
Company* myCompany = new TechCompany("FishC", "Programming Education");
myCompany->printInfo();
delete myCompany;
return 0;
}
在主函数中,创建了一个TechCompany对象,并将其地址赋给指向基类Company的指针myCompany。通过调用指针的printInfo方法,可以触发动态绑定,调用到子类TechCompany的printInfo方法。最后使用delete关键字释放了动态分配的内存。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |