2015-09-27 37 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; 
} 
相关问题