在 VSC++ 2022 窗口中: 如果我有基类:
class Base {
public:
virtual void _ready(){};
}
class Sub:public Base {
public:
//here there is no overwrite
}
class SubSub:public Sub {
public:
//here i like to overwrite the Base _ready function
virtual void _ready(){};
}
这给了我:
error LNK2001: unresolved external symbol "public: virtual void __cdecl fpsgame::subsub::_ready(void)"
windows.64.debug.dll : fatal error LNK1120: 1 unresolved externals
在C++中,子类可以重写基类中的虚函数。这样做的目的是改变基类中虚函数的行为。要从基类重写虚函数,您需要在派生类中声明一个与基类中的虚函数具有相同签名的函数。
查看您提供的代码片段,基类
_ready()
中有一个虚函数Base
。但是,您提供的代码中存在一些语法错误。首先,虚函数应该用 virtual
关键字声明,并且函数名前的下划线 _
在 C++ 中不是必需的(除非你有特殊的命名约定)。此外, Sub
和 SubSub
类中的注释表明您想要重写 _ready()
函数,但您实际上尚未提供它的实现。
这里是一个正确的示例,说明如何在
ready
类中重写 Base
类的 SubSub
函数:
class Base {
public:
virtual void ready() {
// Implementation of the base class version
}
};
class Sub : public Base {
// You can choose to override ready here or not
};
class SubSub : public Sub {
public:
// Correctly overriding the ready function of the Base class
virtual void ready() override {
// Implementation of the SubSub class
}
};
以下几点需要注意:
virtual
关键字将成员函数声明为基类中的虚函数。override
关键字可以帮助编译器检查函数重写是否正确。这是可选的,但建议这样做,因为它可以提高代码可读性并减少错误。关于您提到的错误
error LNK2001: unresolved external symbol
,这通常意味着链接器找不到函数的定义。这可能是由于:
确保所有类和函数定义都包含在您的项目中,并且项目的编译选项设置正确。如果您已在
ready
类中实现了 SubSub
函数并且没有其他编译错误,则应该解决此链接错误。