我在 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 中删除“内联”时,它可以工作,但不知何故 0,4 处的字符没有改变......我真的不知道什么不工作。我在 gcc 编译器中使用 Code::Blocks。
编辑:好的,当我从“move”方法的定义中删除“inline”时,一切正常。但现在我的问题是:为什么我不能在 Screen.cpp 中指定“内联”?