2015-03-02 44 views
-1

我有一個類,我想包含另一個類CRandomSFMT(我沒有自己寫的)的對象。這是test.h有一個課程使用另一個對象

using namespace std; 
#include <cstdlib> 
#include <iostream>  
#include <iomanip> 
#include <sstream> 
#include <fstream> 
#include <stdio.h>  
#include <string.h> 
#include "sfmt.h" 

class Something { 

    public: 
    Something(); 

    private: 
    int seed; 
    CRandomSFMT rangen(); 
    void seed_generator(int, CRandomSFMT&); 
}; 

,這是test.cpp

#include "test.h" 

Something::Something() { 
    seed=1; 
    seed_generator(seed, rangen); 

} 

void Something::seed_generator(int seed, CRandomSFMT& rangen) { 
    rangen.RandomInit(seed); 
} 

當我試着使用g++ -c sfmt.o -msse2 -std=c++11 -O2 test.cpp編譯此我得到

test.cpp: In constructor ‘Something::Something()’: 
test.cpp:5:30: error: invalid use of non-static member function 
    seed_generator(seed, rangen); 

我想聲明seed_generator()靜態但沒」幫助。這裏的類別聲明CRandomSFMT

class CRandomSFMT {     
public: 
    CRandomSFMT(int seed, int IncludeMother = 0) { 
     UseMother = IncludeMother; 
     LastInterval = 0; 
     RandomInit(seed);} 
    void RandomInit(int seed);     
    void RandomInitByArray(int const seeds[], int NumSeeds); 
    int IRandom (int min, int max);    
    int IRandomX (int min, int max);    
    double Random();        
    uint32_t BRandom();       
private: 
    void Init2();        
    void Generate();        
    uint32_t MotherBits();      
    uint32_t ix;         
    uint32_t LastInterval;      
    uint32_t RLimit;        
    uint32_t UseMother;       
    __m128i mask;        
    __m128i state[SFMT_N];      
    uint32_t MotherState[5];      
}; 

任何想法?

回答

2

你已經聲明​​是一個函數;該錯誤是因爲您嘗試像使用對象一樣使用它。

從你desription,「我想包含一個對象」,它應該是一個對象不是一個函數:

CRandomSFMT rangen; // no() 

這將不得不使用它的構造函數初始化:

Something::Something() : seed(1), rangen(seed) {} 
+0

謝謝!現在,我不斷收到錯誤'test.cpp:在構造函數'Something :: Something()': test.cpp:3:23:錯誤:沒有匹配函數調用'CRandomSFMT :: CRandomSFMT()' Something :: Something(){'我試着把它和你的最後一行完全一樣,在'Something :: Something()'裏面放上'rangen(seed)'和'rangen(seed,0)',但是這樣做不會'幫助。 – jorgen 2015-03-02 15:39:25

+0

@jorgen:構造函數,就像我寫的一樣(初始化初始化列表中的對象,使用它的構造函數,在構造函數體中沒有任何內容)應該可以工作。你確定這是你的嘗試?如果你沒有像這樣在列表中初始化它,它將會失敗。 – 2015-03-02 15:41:52

2

你聲明一個函數,而不是對象:

CRandomSFMT rangen(); 

既然你想使用它作爲一個對象應該是這樣的:

CRandomSFMT rangen;