【问题标题】:Namespace inheritance [closed]命名空间继承[关闭]
【发布时间】:2013-08-13 22:37:13
【问题描述】:

首先我不明白为什么会出现这个错误

error: ‘cout’ was not declared in this scope

如下代码

#include <iostream>

namespace a {

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

namespace b {
    using namespace a;

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

int main() {

    b::print();

} 

一般来说,我正在研究命名空间中的继承行为,因为我不需要类本身(无论如何它们只是单例)。使用命名空间方法需要注意什么建议或陷阱?


编辑: 好的,我很抱歉错字。在那种情况下,我可以扩展问题吗?

#include <iostream>

namespace a {


    void print2() {
            print();
    }

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

namespace b {
    using namespace a;

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

int main() {

    b::print2();

}     

这不会编译 错误:“打印”未在此范围内声明

有没有一种方法可以以通用方式模拟类继承?

例如,如果 a 和 b 是类,则将打印 a。如果 print 被声明为 virtual 那么 b 将被打印。

这是否可能,或者命名空间“继承”只是一种廉价的黑客攻击?


编辑 2:

在 print2 输出之前声明 print a.我想我现在的问题是: 在这种情况下有没有办法或模拟虚拟关键字?这样下面会分别打印 b 和 c。

#include <iostream>

namespace a {

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

    void print2() {
            print();
    }

}       

namespace b {
    using namespace a;

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

namespace c {

    using namespace a;

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

int main() {

    b::print2();
    c::print2();

}      

【问题讨论】:

  • std::cout - 注意两个冒号。
  • std:goto 的标签。标签后面的语句是cout &lt;&lt; &lt;&lt; "a" &lt;&lt; std::endl;
  • 这个问题似乎是题外话,因为它只是一个错字。
  • 没有命名空间继承之类的东西。如果您需要继承/多态,请使用类。
  • 你应该一次问一个问题,而不是修改你的问题来每次问不同的东西。

标签: c++ namespaces


【解决方案1】:

你拼错了std::cout (std:cout)。

在您的代码中,std:goto 声明了一个标签。声明的其余部分是:

cout << "a" << std::endl; 

因此,编译器抱怨未知标识符 cout

更新:

修正错字后,将函数顺序更改为:

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

void print2() {
        print();
}

更新 2:

在您再次编辑问题后,它完全失去了最初的含义。但答案是No。不,你不能继承命名空间。

【讨论】:

  • 我可能没有正确地考虑这整个面向对象的事情。感谢您的宝贵时间。
猜你喜欢
  • 2013-03-10
  • 1970-01-01
  • 2017-12-10
  • 1970-01-01
  • 1970-01-01
  • 2013-12-30
  • 2017-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多