我在程序中使用虚拟功能时收到 LNK2005、LNK2001 和 LNK1120
我是一个初学者,所以这个问题对你来说可能看起来微不足道。 所以我有以下文件:
- base.h
- 衍生
- .hbase.cpp
- 衍生
- .cppTestCpp.cpp
base.h
#include <iostream>
namespace App
{
class Base
{
public:
virtual void Print();
};
}
base.cpp
#include "base.h"
namespace App
{
}
衍生.h
#include "base.h"
class Derived : public App::Base
{
public:
void Print();
};
衍生.cpp
#include "derived.h"
void Derived::Print()
{
std::cout << "This works!! form Derived class\n";
}
最后 TestCpp.cpp
#include "derived.h"
int main()
{
std::cout << "Hello World!\n";
Derived d;
d.Print();
return 0;
}
我不知道我做错了什么。请帮帮我。
I am a beginner so this problem might seem trivial to you.
So I have the following files:
- base.h
- derived.h
- base.cpp
- derived.cpp
- TestCpp.cpp
base.h
#include <iostream>
namespace App
{
class Base
{
public:
virtual void Print();
};
}
base.cpp
#include "base.h"
namespace App
{
}
derived.h
#include "base.h"
class Derived : public App::Base
{
public:
void Print();
};
derived.cpp
#include "derived.h"
void Derived::Print()
{
std::cout << "This works!! form Derived class\n";
}
and at last
TestCpp.cpp
#include "derived.h"
int main()
{
std::cout << "Hello World!\n";
Derived d;
d.Print();
return 0;
}
I am getting the following Linker error:
I don't know what it is I am doing wrong. Please help me out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您仅在
Base
类中声明虚函数Print
,但没有定义它。以及C++03 标准:10.3 虚函数 [class.virtual]
因此解决这个问题的方法是在类
Base
中实现/定义virtual
成员函数Print
或者通过将类Base
中的声明替换为virtual void Print() = 0;
使其成为纯虚拟解决方案 1
Base.cpp
解决方案 1 DEMO
解决方案 2
Base.h
解决方案 2 演示
The problem is that you've only declared the virtual function
Print
in classBase
but not defined it.And from C++03 Standard: 10.3 Virtual functions [class.virtual]
So the way to solve this problem would be to either implement/define the
virtual
member functionPrint
in classBase
or make it pure virtual by replacing the declaration withvirtual void Print() = 0;
inside classBase
Solution 1
Base.cpp
Solution 1 DEMO
Solution 2
Base.h
Solution 2 DEMO
只需在
base.cpp
文件中添加Print()
的定义即可:它里面可能没有任何内容,但它应该在那里。
或者通过使其纯粹来指示
Print()
在派生类中定义:这2 个选项中的任何一个都有效。另外,在派生类中,最好将
Print()
设为override
:(单击此处了解原因)Just add a definition for
Print()
in thebase.cpp
file:It may not have anything inside it, but it should be there.
Or indicate
Print()
to be defined in the derived class by making it pure:Any one of the 2 options work. Also in your derived class it's better to make
Print()
asoverride
: (Click here to know why)