Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为了输出特定项,哪些功能需要是虚拟的?_C++_Oop_Virtual Functions - Fatal编程技术网

C++ 为了输出特定项,哪些功能需要是虚拟的?

C++ 为了输出特定项,哪些功能需要是虚拟的?,c++,oop,virtual-functions,C++,Oop,Virtual Functions,我正在尝试输出以下内容: apple banana orange banana 为了输出,我必须使我的函数虚拟吗 class Red { public: void PrintMe() { Foo(); Bar(); } void Foo() { printf("pear\n"); } void Bar() { printf("lemon\n"); } }; class Green : public Red { public: void PrintMe() {

我正在尝试输出以下内容:

apple
banana
orange
banana
为了输出,我必须使我的函数虚拟吗

class Red
{
public:
    void PrintMe() { Foo(); Bar(); }
    void Foo() { printf("pear\n"); }
    void Bar() { printf("lemon\n"); }
};

class Green : public Red
{
public:
    void PrintMe() { Bar (); Foo(); }
    void Foo() { printf("apple\n"); }
    void Bar() { printf("banana\n"); }
};

class Blue : public Green
{
public:
    void Foo() { printf("orange\n"); }
    void Bar() { printf("grape\n"); }
};
int main(int argc, char* argv[])
{
    Green g;
    Blue b;

    Red *pR1 = &g;
    Red *pR2 = &b;
    pR1->PrintMe();
    pR2->PrintMe();
}

是的,否则您将打印两个红色。

红色::Foo和红色::Bar需要是虚拟的。

您的代码似乎存在一些问题:您定义了一个名为Red的类,但绿色继承了一个名为Red的类


无论如何,如果red是您的基类,并且您希望其他类重写其方法,那么您需要将它们声明为虚拟的。

简短回答:PrintMe需要是虚拟的

说明:

由于要调用基类指针指向的专用对象的方法,因此需要将该方法设置为虚拟方法

// Base class pointer pointing to specialized class
Red *pR1 = new Green();

// If PrintMe() is not virtual, this call will be Red::PrintMe(). 
// If you want to call Green::PrintMe, make it virtual.
pR1->PrintMe();

哈哈!没有人把这件事做对了

您需要将PrintMe设置为虚拟,因为foo/bar的顺序可以更改

你需要将Foo和Bar虚拟化,因为它们做的事情不同

您需要将析构函数设置为虚拟的,因为您正在实现多态高层结构。这一个甚至不在你的代码中。您特定的testmain不需要它,但最合理、非琐碎的使用将需要它


编辑:好吧,也许我也弄错了。如果您不希望PrintMe在通过基指针使用时实际重写行为,那么它不应该是虚拟的。你的代码有点混乱。没有人会这样做。

在当前设置下,您无法获得苹果香蕉橙香蕉作为输出,因为:

要使用红色*pR1打印苹果香蕉,必须将Foo和Bar设置为虚拟。 一旦将函数声明为虚拟函数,它在所有派生类中都将保持虚拟状态。 现在,由于酒吧是虚拟的,pR2->PrintMe将打印橙色葡萄-它不可能打印香蕉。
Green::PrintMe调用Foo和Bar的顺序与Red::PrintMe相反。@Larsman是的,但如果我没有弄错的话,他想打印apple banana,这意味着他需要调用Red::PrintMe,而Green::PrintMe是一个红鲱鱼。OP可以用蓝色声明Bar const。那么它就不会是一个覆盖。@Noah Roberts:我只是说,在当前的设置中,这是不可能的,因为OP的问题只是让一些函数成为虚拟的。好吧,当前的设置也没有任何虚拟函数,所以就这样吧;我得出了同样的结论,+1。也许@Noah Roberts想给我更迂腐正确的答案投票;投票结束了这个问题。太多的问题无法回答。没有投票结束,不同意-1。这个问题有两个正确答案是和其他问题,或者不是因为。值得思考。20美元表示OP从未选择任何答案,也从未解决过有意义的问题。我不是在第一个命题上下注。所以我不知道接下来该走什么路。我所有的问题都与一个项目有关,这是唯一阻碍我的事情。我完全意识到这种方式不是最熟练的,但它是我必须使用的。