在类定义之外内联方法时"Undefined reference"

"Undefined reference" when inlining method outside of the class definition

本文关键字:方法 Undefined reference 定义      更新时间:2023-10-16

我在屏幕中有这个类(完整代码)。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中独占使用。