2015-09-27 12 views
-3

我想在同一個類函數上做具體語句。 還有就是我triying什麼使C++ - 具有不同語句的類的函數

#include <stdio.h> 

class animal 
{ 
    public: 
     void Talk(); 
}; 

int main() 
{ 
    animal dog; 
    animal cat; 

    dog::Talk() 
    { 
     printf("Wof"); 
    }; 

    cat::Talk() 
    { 
     printf("Meow"); 
    }; 

    dog.Talk(); 
    cat.Talk(); 

    return 0; 
} 

我也與類繼承嘗試的一個例子,像

#include <stdio.h> 

class cat 
{ 
    public: 
     void Talk() 
     { 
     printf("Meow"); 
     }; 
}; 

class dog 
{ 
    public: 
     void Talk() 
     { 
     printf("Wof"); 
     } 
}; 

class animal{}; 

int main() 
{ 
    animal Schnauzer: public dog; 
    animal Siamese: public cat; 

    Schnauzer.Talk(); 
    Siamese.Talk(); 

    return 0; 
} 

有辦法做這樣的事情?

+1

http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – juanchopanza

+0

去閱讀關於繼承:https://msdn.microsoft.com/en-us /library/a48h1tew.aspx – CinCout

+0

爲什麼這些函數在'main'內執行????? –

回答

0

這是一個非常基本的事情要做的c + +。你只需要知道一點關於繼承。但是,我猜你是新來的C++,並沒有太多的使用繼承經驗。所以,我給你一個簡單的解決方案,使用下面的類繼承。隨意問我是否有任何困惑。

#include <iostream> 

using namespace std; 

class animal { 
    public: 
    virtual void Talk() {cout << "default animal talk" << endl;} 
}; 

class dog: public animal { 
    public: 
    void Talk() {cout << "Wof" << endl;} 
}; 

class cat: public animal { 
    public: 
    void Talk() {cout << "Meow" << endl;} 
}; 

int main() 
{ 
    dog Schnauzer; 
    cat Siamese; 

    Schnauzer.Talk(); 
    Siamese.Talk(); 
    return 0; 
} 
相關問題