在类定义之外的内联方法时使用“未定义的引用”

时间:2013-08-11 12:18:03

标签: c++

我在Screen.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编译器的Code :: Blocks。

编辑:当我从“移动”方法的定义中删除“内联”时,一切正常。但现在我的问题是:为什么我不能在Screen.cpp中指定“内联”?

2 个答案:

答案 0 :(得分:0)

你有内联cpp文件删除内联,它会没事的。我的意思是Screen :: move功能。替代移动定义到头文件。

答案 1 :(得分:0)

将其放入* .h或将其设为私有,并在* cpp中使用它。