1
我有一个C++“接口”类,并收到以下错误在编译的时候:静态方法
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;
}
嗯,我已经试过了......由于抽象类不能直接初始化,所以我真的需要一个静态类函数。 – alex 2011-12-21 19:18:23
它将是静态的 - 在.h文件中保留静态但从.cpp文件中移除静态(静态在两个位置都有不同的内涵,并且将它放在.h文件中就足够了,它在.cpp文件中) – necromancer 2011-12-21 19:21:25
你如何认为你真的需要一个静态函数?你有没有得到某种错误?或者只是你的直觉?因为C++中的“静态”意味着“链接不可见”。它不像C#和Java那样意味着“非实例”。所以,你说这个函数是不可链接的,当然以后链接器找不到它。 – 2011-12-21 19:24:13