我有一个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;
}

最佳答案

尝试:

void Serializable::writeString (...) {
 // ...
}

(尝试不带static,并添加类名)

关于c++ - C++中的静态方法 “Interface”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8595030/

10-09 15:53