重複の可能性:
C++: 静的クラス メンバーへの未定義の参照
ここでの私の目標は、オブジェクトを保持するコンテナー オブジェクトを作成することです。これを行うには、ポインターのベクトルを使用することにしました。
コンテナ オブジェクトとは別に、関数 print を持つ抽象基本クラスがあります。派生クラスは関数をオーバーライドできるため、これは仮想関数です。最後に、この派生クラスからオブジェクトを作成し、コンテナーに格納しようとします。
以下は、抽象クラスの定義を保持するヘッダー ファイルです。
Element.h
#ifndef ELEMENT_H
#define ELEMENT_H
using namespace std;
//Abstract class with pure virtual functions
class Element{
public:
virtual void print()=0;
};
#endif
以下では、コンテナのテンプレート クラスを作成しようとしています。コンテナーを操作するためのメンバー関数と共に、順序の反転、印刷など。
Elements.h
#include <vector>
#include <Element.h>
using namespace std;
//Creating a class which will hold the vector of pointers
class Elements{
public:
static vector<Element*> elements;
static void addElement(Element*e){
elements.push_back(e);
}
static unsigned int size() {
return elements.size();
}
static void print_all() {
for (int i=0;i<elements.size();i++){
elements[i]->print ();
}
}
static void reverse(){
int i=0;
int j=elements.size()-1;
while(!(i==j)&&!(i>j)){
Element*temp;
temp=elements[i];
elements[i]=elements[j];
elements[j]=temp;
i++;
j--;
}
}
};
以下では、いくつかのメンバー関数とともに抽象クラス Element のインスタンスを作成しています。私が構築しようとしているコンテナは、この種のオブジェクトを保持します。
ええ
#include <iostream>
#include <istream>
#include <ostream>
#include <vector>
#include <Element.h>
using namespace std;
class I:public Element{
int myInteger;
public:
I();
I(int);
void setI(int);
int getI(void);
void print();
};
I::I(int inInteger){
setI(inInteger);}
void I::setI(int inInteger){
myInteger=inInteger;
}
int I::getI(){
return myInteger;
}
void I::print(){
cout<<"\nThe value stored in the Integer:"<<getI();
}
以下では、タイプ I のオブジェクトを作成しようとしています。値を入力して、その出力を取得します。次に、それらをコンテナに「押し込み」ます。main.cpp
#include <iostream>
#include <istream>
#include <ostream>
#include <vector>
#include "Element.h"
#include "I.h"
#include "Elements.h"
using namespace std;
int main() {
int userInt;
Element*element;
cout<<"enter an integer";
cin>>userInt;
element = new I(userInt);
element->print();
Elements::addElement(element);
Element*element2;
cout<<"enter an integer";
cin>>userInt;
element2=new I(userInt);
element2->print();
Elements::addElement(element2);
Elements::print_all();
Elements::reverse();
int i=Elements::size();
cout<<i;
}
gcc GNUコンパイラを使用して、Codeblocks 10.05を使用してコンパイルしています。上記の main.cpp をビルドすると、次のエラーが表示されます: '要素::要素' への未定義の参照が各機能の要素: addElement,size,....etc の Elements.h にあります。
このフォーラムに投稿するのはこれが初めてです。ヘルプやコメントは大歓迎です。