【问题标题】:C++ calling parent function only works when using a pointer [duplicate]C ++调用父函数仅在使用指针时有效[重复]
【发布时间】:2013-06-18 17:57:02
【问题描述】:

在这两个程序中,第二个可以工作,但第一个不能编译。这怎么可能?唯一的区别是,在第二版中 bar 是一个指针,而在第一版中它不是。

版本一:(不编译)

#include <iostream>


class Foo{

    public:
        void print(){
            std::cout << "asdasd" << std::endl;
        }

};

class Bar : public Foo{


};
int main(){
    Bar bar();
    bar.print();
}

还有第二个版本:

#include <iostream>

class Foo{

    public:
        void print(){
            std::cout << "asdasd" << std::endl;
        }

};

class Bar : public Foo{


};
int main(){
    Bar* bar = new Bar();
    bar->print();
}

【问题讨论】:

  • 另一个最令人头疼的解析问题...
  • 为什么投反对票?非常公平的问题,经过深入研究。对于这种情况,谷歌并不容易。
  • 也就是说你需要发布你的错误信息。最好用谷歌搜索一下,看看是什么原因造成的。
  • 最令人头疼的解析又来了。
  • windows 8 中一些奇怪的语言设置导致我的错误消息是带有英语和奇怪符号的破碎瑞典语,我想发布它但没有意义。

标签: c++ inheritance


【解决方案1】:
Bar bar();

是一个函数的声明。

Bar bar;

是你的朋友。

【讨论】:

    猜你喜欢
    • 2014-02-22
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多