创建自己定义的Screen类,在定义函数时,将成员函数定义为inline函数,链接时报出error:
>demo.obj : error LNK2019: 无法解析的外部符号
> "public: class Screen & __thiscall Screen::set(char)" (?set@Screen@@QAEAAV1@D@Z)
> 该符号在函数 _main 中被引用
删除定义处的inline标识就没问题了,很奇怪为什么。
Screen.h
#pragma once
#include <iostream>
#include <string>
class Screen {
public:
typedef std::string::size_type pos;
Screen() = default;
Screen(pos ht, pos wd)
: content(ht * wd, ' ') {}
Screen(pos ht, pos wd, char c)
: height(ht), width(wd), content(ht * wd, c) {};
char get() const {
return content[cursor];
}
char get(pos ht, pos wd) const;
Screen &move(pos r, pos c);
void accessTime() const {
++times;
}
Screen &set(char);
Screen &set(pos, pos, char);
const Screen &display(std::ostream &os) const {
os << content;
return *this;
}
Screen &display(std::ostream &os) {
os << content;
return *this;
}
~Screen() {};
private:
void do_display(std::ostream &os) const {
os << content;
}
pos cursor = 0;
pos height = 0, width = 0;
std::string content;
mutable size_t times = 0;
};
Screen.cpp
#include "pch.h"
#include "Screen.h"
char Screen::get(pos r, pos c) const {
pos row = r * width;
return content[row + c];
}
Screen &Screen::move(pos r, pos c) {
pos row = r * width;
cursor = row + c;
return *this;
}
inline Screen& Screen::set(char c) {
content[cursor] = c;
return *this;
}
Screen& Screen::set(pos ht, pos wd, char c) {
content[ht * width + wd] = c;
return *this;
}
main.cpp
Screen myScreen(5, 5, 'X');
myScreen.move(4, 0).set('#').display(cout);
cout << "\n";
myScreen.display(cout);
cout << "\n";
常见的该问题的解决方法可以参考:https://blog.csdn.net/qq_25810695/article/details/80282515