C++调用父函数仅在使用指针时有效

标签 c++ inheritance

<分区>

在这两个程序中,第二个可以运行,但第一个无法编译。这怎么可能?唯一的区别是在版本二中 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();
}

最佳答案

Bar bar();

是一个函数的声明。

Bar bar;

是你的 friend 。

关于C++调用父函数仅在使用指针时有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17175712/

相关文章:

c++ - 在 Clang 中使用 MSVC 预处理器 'charizing' 运算符

c# - 如何在 XP 下工作的 C# 代码中使用 c++ dll?

c++ - 有条件地从两个类中的任何一个继承

python - 使用 Python 覆盖属性

c# - 具有多级继承的 base.Method() 未被调用?

c++ - MSVC2010中不同分辨率的图标

c++ - Rcpp 编译属性不可调用

c++ - socket() 和bind() 的行为如何?

java接口(interface)和子类

c++ - 避免使用虚方法构造具有空基类的构造函数