Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/158.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++_Class_Object - Fatal编程技术网

C++ 如何为不同的类声明相同的对象名?

C++ 如何为不同的类声明相同的对象名?,c++,class,object,C++,Class,Object,通常这是我的代码 #include <iostream> using namespace std; class On { public: int value; }; class Off { public: int value; }; int main() { On push; push.value = 1; cout << push.value << endl; return 0; }

通常这是我的代码

#include <iostream>
using namespace std;

class On {
    public:
    int value;
};

class Off {
    public:
    int value;
};


int main() {
    On push;
    push.value = 1;
    cout << push.value << endl;

    return 0;
}
#包括
使用名称空间std;
上课{
公众:
int值;
};
下课{
公众:
int值;
};
int main(){
推送;
push.value=1;

不能将每个人放在不同的名称空间中:

namespace N1 { On push; }
namespace N2 { On push; }
用法:

 N1::push.value
 N2::push.value
您可以使用作用域:

#include <iostream>
using namespace std;

class On {
    public:
    int value;
};

class Off {
    public:
    int value;
};


int main() {
    {
        On push; // 'push' object for the class -> On
        push.value = 1;
        cout << push.value << endl;
    }
    {
        Off push; // 'push' object for the class -> Off
        push.value = 0;
        cout << push.value << endl; 
        // Here's the problem. How can I can define it's coming from an specific/defferent object?
    }

    return 0;
}
#包括
使用名称空间std;
上课{
公众:
int值;
};
下课{
公众:
int值;
};
int main(){
{
On push;类的//“push”对象->On
push.value=1;

可能不行?你为什么要这样做?你无法区分
push
push
之间的区别,那么为什么你想让它们成为两个对象呢?名字阴影几乎总是一个bug巢穴,不能推荐。谢谢,@ThomasSablik你的代码为我工作。实际上,没有必要。我只是在想我是否需要这样做在其他任何地方,我应该如何编写这段代码。这就是为什么我要问这个问题。感谢大家提供的建议。:)谢谢@ouchane,你的代码也可以工作。顺便说一句,在你的代码名称空间中,N2应该是{Off push;}是的,你可以使用任何其他类型:)
#include <iostream>
using namespace std;

class On {
    public:
    int value;
};

class Off {
    public:
    int value;
};


int main() {
    {
        On push; // 'push' object for the class -> On
        push.value = 1;
        cout << push.value << endl;
    }
    {
        Off push; // 'push' object for the class -> Off
        push.value = 0;
        cout << push.value << endl; 
        // Here's the problem. How can I can define it's coming from an specific/defferent object?
    }

    return 0;
}