首页 > 解决方案 > 如何从嵌套在命名空间中的类中调用成员函数?

问题描述

我想从不同的文件调用嵌套在命名空间中的类成员函数,但我不知道如何。

例如:

如何调用someFunc()位于 code.h 中并嵌套在 main.cpp 命名空间“程序”中的类成员函数。

//code.h
#include <iostream>

namespace program
class test {
private:
    int x;
public:
    test()
    {
        test::x = 10;
    };

    someFunc()
    {
        cout << x << " ";
    };
};

标签: c++oop

解决方案


你的代码有一些问题

#include <iostream>

namespace program { // <-- braces missing

class test
{
private:
    int x;
public:
    test()
    {
        test::x = 10; // <-- test:: is unnecessary but no error
    };

    void someFunc() // <-- return type missing
    {
        std::cout << x << " "; // <-- namespace std missing
    };
};

} // <-- braces missing

int main() {
    program::test t;
    t.someFunc();
}

推荐阅读