2011-12-21 9 views
1

私はC++「インターフェイス」クラスを持っているし、コンパイルしようとしたときに次のエラーを取得する:staticメソッド++「インターフェイス」

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; 
} 

答えて

7

試してみてください。

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

(静的ずにそれを試して、そしてクラス名を追加します)

+0

さて、私はそれをもう一度試みました...抽象クラスを直接初期化することはできないので、ここには静的なクラス関数が本当に必要です。 – alex

+1

これは静的になります。静的に.hファイルに静的を保持しますが、.cppファイルから静的を削除します(静的には両方の場所で異なる意味があり、それを.hファイルに入れるだけで十分です.cppファイル) – necromancer

+0

ここに静的関数が本当に必要であることをどう思いますか?何らかのエラーがありましたか?それともあなたの腸の感覚ですか? C++のこの文脈での「静的」とは「リンクできない」という意味です。 C#やJavaのように、「インスタンスではない」という意味ではありません。したがって、関数はリンク可能ではなく、後でリンカーがそれを見つけることができないと言っています。 –

関連する問題