【问题标题】:Static method in C++ "Interface"C++“接口”中的静态方法
【发布时间】:2011-12-21 19:11:48
【问题描述】:

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

【问题讨论】:

    标签: c++ interface static


    【解决方案1】:

    尝试:

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

    (不加静态试试,加上类名)

    【讨论】:

    • 嗯,我已经试过了……既然抽象类不能直接初始化,我这里真的需要一个静态类函数。
    • 它将是静态的——将静态保留在 .h 文件中,但从 .cpp 文件中删除静态(静态在两个位置都有不同的含义,将其放在 .h 文件中就足够了) h 文件,不正确的放在 .cpp 文件中)
    • 你怎么知道你真的需要一个静态函数?你有什么错误吗?还是只是你的直觉?因为在 C++ 中的这种上下文中的“静态”意味着“链接不可见”。它并不像在 C# 和 Java 中那样表示“非实例”。所以,你是说这个函数是不可链接的,当然后来链接器也找不到它。
    • 哦,我明白了。现在编译...太棒了。
    猜你喜欢
    • 2015-06-15
    • 2014-06-02
    • 2017-12-04
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    相关资源
    最近更新 更多