我有一个C ++“Interface”类,在尝试编译时会出现以下错误:
Undefined symbols for architecture x86_64:
"Serializable::writeString(std::ostream&, std::string)", referenced from:
Person::writeObject(std::ostream&) in Person.o
Artist::writeObject(std::ostream&) in Artist.o
"Serializable::readString(std::istream&)", referenced from:
Person::readObject(std::istream&) in Person.o
Artist::readObject(std::istream&) in Artist.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
是否可以在抽象类中实现静态方法?
我的实现看起来像这样。
.h文件
#ifndef Ex04_Serializable_h
#define Ex04_Serializable_h
using namespace std;
class Serializable {
public:
virtual void writeObject(ostream &out) = 0;
virtual void readObject(istream &in) = 0;
static void writeString(ostream &out, string str);
static string readString(istream &in);
};
#endif
.cpp文件
#include <iostream>
#include "Serializable.h"
using namespace std;
static void writeString(ostream &out, string str) {
int length = str.length();
// write string length first
out.write((char*) &length, sizeof(int));
// write string itself
out.write((char*) str.c_str(), length);
}
static string readString(istream &in) {
int length;
string s;
// read string length first
in.read((char*) &length, sizeof(int));
s.resize(length);
// read string itself
in.read((char*) s.c_str(), length);
return s;
}
答案 0 :(得分:7)
尝试:
void Serializable::writeString (...) {
// ...
}
(尝试没有静态,并添加类名)