C ++编译器错误中的简单类继承[重复]

Posted

技术标签:

【中文标题】C ++编译器错误中的简单类继承[重复]【英文标题】:simple class inheritance in c++ compiler errors [duplicate] 【发布时间】:2013-12-02 05:01:36 【问题描述】:

我希望我的 Dog 类正确继承 Pet 中的函数,以便 main 中的代码能够正确执行。编译器警告从基类 Pet 调用私有方法。

主要:

Dog * d = new Dog( "Muffin" );

cout << "The " << d->getVariety( ) << " " << d->getName( ) << " speaks by saying " << d->speak( ) << endl;

类:

class Pet

public:
Pet( );
Pet( std::string name, std::string variety, std::string says )


    myName=name;
    myVariety=variety;
    howIspeak=says;


std::string getName( ) const

    return myName;
;
public:
std::string getVariety( ) const

    return myVariety;
;

std::string speak() const


    return howIspeak;
;

protected:
std::string myName;
std::string myVariety;
std::string howIspeak;
;

class Dog: Pet

public:
Dog( );
Dog( std::string name );

virtual void speak( );
;

【问题讨论】:

speak 需要在 class Pet 中是虚拟的。另外,我想你的意思是class Dog : public Pet 【参考方案1】:

C++ 默认为私有继承。因此使用

class Dog: public Pet

【讨论】:

【参考方案2】:

类默认有私有继承

 class Dog: public Pet

【讨论】:

以上是关于C ++编译器错误中的简单类继承[重复]的主要内容,如果未能解决你的问题,请参考以下文章

另一个类中的方法“不存在”编译器错误[重复]

Makefile:链接器错误[重复]

在C ++中的继承上下文中按值传递对象[重复]

C ++静态库中的模板方法[重复]

c ++继承编译问题未定义对派生类的引用[重复]

C/C++ union 中的问题