2017-10-28 90 views
-4

我依稀記得在C++中看到一個例子是一個類中有一個成員對象,第一個類暴露了屬於第二個類的函數,就好像它在哪裏。繼承自has-a關係

這裏解釋一下我的意思是一個例子:

class Engine{ 
    int cylinders; 
public: 
/* ... */ 
    int getCylindersCount() { return this->cylinders;} 
}; 

class Car { 
    Engine engine; 
public: 
    /* define getCylindersCount() as if it were a function in class Car */ 
    /* something like Car::getCylindersCount is engine.getCylindersCount(); */ 
}; 

所以基本上級轎車的用戶可以這樣做:

Car mytoyota; 
mytoyota.getCylindersCount(); 

現在,我不是在談論一個簡單的包裝,如:

class Car { 
    Engine engine; 
public: 
    int getCylindersCount() { return engine.getCylindersCount();} 
}; 

你能幫我記住語法是怎麼實現的嗎?

謝謝。

+2

出了什麼問題'INT getCylindersCount(){返回engine.getCylindersCount(); }'? – DimChtz

+0

@DimChtz沒有錯。只是想知道我的記憶是否正確。 正如我所提及的,如果我的記憶爲我服務,我確實記得在C++中有一些可以爲您提供的東西,爲什麼不使用它? – hebbo

回答

0

有沒有這樣的事情。

但你指的是語法的確存在:它改變繼承成員函數訪問預選賽棄用的方式:

class A 
{ 
    public: 
    void foo() {} 
}; 

class B : A 
{ 
    public: 
    A::foo; // Otherwise A::foo() would be private. 
    // A non-deprecated way to do the same thing: 
    // using A::foo; 
};