gpt4 book ai didi

c++ - 面向对象编程逻辑

转载 作者:可可西里 更新时间:2023-11-01 17:09:10 25 4
gpt4 key购买 nike

我正在学习 C++ 中 OOP 的基本概念,我遇到了一个逻辑问题。

#include <iostream>
#include <conio.h>

using namespace std;

class A {
int i;
public:
void set(int x) {
i=x;
}
int get() {
return i;
}
void cpy(A x) {
i=x.i;
}
};

int main()
{
A x, y;
x.set(10);
y.set(20);

cout << x.get() << "\t" << y.get() << endl;
x.cpy(y);
cout << x.get() << "\t" << y.get() << endl;
getch();
}

我想知道在上面的代码中,为什么我能够访问 x.i [第 19 行],它是不同对象中的私有(private)成员。私有(private)范围是否限制为相同类即使对象作为参数传递?

最佳答案

private 在 C++ 中意味着对类私有(private),而不是对对象私有(private)。两种解释都是可能的,确实有些语言选择了另一种。但大多数语言在这一点上都像 C++,允许同一类的对象访问另一个实例的私有(private)成员。

关于c++ - 面向对象编程逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10872168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com