在类定义之外内联方法时"Undefined reference"
"Undefined reference" when inlining method outside of the class definition
我在屏幕中有这个类(完整代码)。h:
#include <string>
#include <iostream>
class Screen {
using pos = std::string::size_type;
private:
pos cursor = 0;
pos height = 0, width = 0;
std::string contents;
public:
Screen() = default; // needed because Screen has another constructor
Screen(pos ht, pos wd) : Screen(ht, wd, ' ') {}
Screen(pos ht, pos wd, char c): height(ht), width(wd),
contents(ht * wd, c) { }
char get() const {
return contents[cursor];
}
Screen& move(pos r, pos c);
inline char get(pos ht, pos wd) const; // explicitly inline
Screen& set(char);
const Screen& display(std::ostream&) const;
Screen& display(std::ostream&);
private:
void doDisplay(std::ostream&) const;
};
及其在Screen.cpp:中的实现
#include "Screen.h"
#include <iostream>
char Screen::get(pos r, pos c) const // declared as inline in the class
{
pos row = r * width; // compute row location
return contents[row + c]; // return character at the given column
}
inline Screen& Screen::move(pos r, pos c) {
pos row = r * width;
cursor = row + c;
return *this;
}
Screen& Screen::set(char c) {
contents[cursor] = c;
return *this;
}
Screen& Screen::display(std::ostream& outputStream) {
doDisplay(outputStream);
return *this;
}
const Screen& Screen::display(std::ostream& outputStream) const {
doDisplay(outputStream);
return *this;
}
void Screen::doDisplay(std::ostream& outputStream) const {
for (unsigned h = 0; h < height; ++h) {
for (unsigned w = 0; w < width; ++w) {
outputStream << contents[h*w];
}
outputStream << std::endl;
}
}
我的主文件:
#include "Screen.h"
#include <iostream>
int main() {
Screen myScreen(5, 5, 'X');
myScreen.move(0,4).set('#').display(std::cout);
std::cout << std::endl;
int returnCode = EXIT_SUCCESS;
return returnCode;
}
这会产生以下链接器错误:对"Screen::move(unsigned long-long,unsigned long-long)"的未定义引用
当我从Screen::move中删除"inline"时,它是有效的,但不知何故,0.4处的字符没有改变。。。我真的不知道什么不起作用。我在gcc编译器中使用代码::块。
编辑:好吧,当我从"移动"方法的定义中删除"内联"时,一切都很好。但现在我的问题是:为什么我不能在Screen.cpp中指定"inline"?
您在cpp文件中有inline移除inline,这将很好。我指的是屏幕::移动功能。将定义移动到头文件的替代方法。
将其放入*.h中,或者将其设为私有并在*cpp中独占使用。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 没有为自己的结构调用列表推回方法
- 尝试使用 extern "C" 调用 C 中的C++方法,得到"undefined reference to"对象的链接器错误
- undefined 方法 'split' for nil:nilClass
- "undefined reference"从静态方法访问的模板类的静态成员
- 在类定义之外内联方法时"Undefined reference"