gpt4 book ai didi

c++ - C++ 中的静态方法 "Interface"

转载 作者:行者123 更新时间:2023-11-30 00:39:33 24 4
gpt4 key购买 nike

我有一个 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 (...) {
// ...
}

(尝试不使用静态,并添加类名)

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com