You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于多态与虚函数的C++简单程序输出异常问题排查

问题分析与修复方案

你的代码里有三个关键问题导致多态未生效,甚至Server的print()本身也无法正常工作:

1. 父类的print()未声明为虚函数

C++中只有虚函数才能通过基类指针/引用触发多态调用子类的实现。你的Employee类里print()是普通成员函数,所以Employee* a = new Server;调用a->print()时,只会执行父类的print(),不会动态绑定到Server的版本。

修复:在Employee类的print()前加上virtual关键字:

class Employee
{
public:
    virtual void job();
    virtual void print(); // 添加virtual声明
};

2. Server类的print()未正确输出内容

Server.cpp里的print()函数仅写了字符串字面量,没有用cout输出,就算调用了也看不到任何内容:

void Server::print() {
    "I am a server!
"; // 这只是未使用的字符串常量,不会输出到控制台
}

修复:补充cout输出语句:

void Server::print() {
    cout << "I am a server!
" << endl;
}

3. Server.h里的语法错误

#include "Employee.h";后面多了一个分号,会导致编译错误,需要去掉:

// 错误写法
#include "Employee.h";
// 正确写法
#include "Employee.h"

修复后关键代码示例

Employee.h

#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <iostream>

using namespace std;

class Employee
{
public:
    virtual void job();
    virtual void print(); // 声明为虚函数
};
#endif

Server.cpp

#include "Server.h"

void Server::job() {
    cout << "Serve tables
";
    print();
}

void Server::print() {
    cout << "I am a server!
" << endl; // 正确输出内容
}

修复后运行结果

执行main函数会输出:

Serve tables
I am a server!

I am a server!

Employee status yet to be determined.

New employee

此时a->print()会正确调用Server类的print()实现,多态机制生效。

内容的提问来源于stack exchange,提问作者ndalzell1219

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 12:10:24