命名空间中不能使用转发声明的替代方法

问题描述 投票:0回答:1

我知道,作为类的前向声明的替代方案,你可以使用C-style identifiersdeclarations,就像这样。

//instead of
class Foo;

void func(Foo* foo);

//do

void func(class Foo* foo);

但是在这种情况下,我遇到了一个问题,只是在改变了我的编译器(Visual Studio)的设置之后。我认为它被设置为允许的,或者说没有执行许多一致性标准。

namespace Foo
{
    void func(class Bar* bar) {}
}

class Bar {};

int main()
{
    Bar bar;
    Foo::func(&bar); // argument of type "Bar *" is incompatible with parameter of type "Foo::Bar *"    
// cannot convert argument 1 from 'Bar *' to 'Foo::Bar *'   

}

如果Foo是一个类,那么这样做就可以了。难道没有一种方法可以用命名空间来实现吗?

c++ forward-declaration
1个回答
1
投票

错误很简单。你调用了类Bar,然后在那之后声明了它。下面是更正后的代码。

#include <iostream>
using namespace std;  

class Bar {};
namespace Foo
{
    void func(Bar* bar) { cout << "Hello World!" << endl; }
}
//class Bar {};     A Functions/Class/Struct etc's prototype must be defined before its used/called in a function

int main()
{
    Bar bar;
    Foo::func(&bar); // argument of type "Bar *" is incompatible with parameter of type "Foo::Bar *"    
                     // cannot convert argument 1 from 'Bar *' to 'Foo::Bar *'

    return EXIT_SUCCESS;    //-- My Special Touch
}

每当一个函数被调用时,它都会在其调用的函数上面查看其原型或定义是否存在。

© www.soinside.com 2019 - 2024. All rights reserved.