Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

常对象,只能调用常成员函数、更新常成员变量? #41

Closed
hbsun2113 opened this issue Jun 20, 2019 · 4 comments
Closed

Comments

@hbsun2113
Copy link

请问常成员变量为什么要被更新?

@huihut
Copy link
Owner

huihut commented Jun 20, 2019

当常成员变量是指针的时候可以更新,如 #12 (comment) 中的 c

@hbsun2113
Copy link
Author

请问常成员变量是“常量指针”还是“常量指针”?(c应该是常量指针吧?)
当该指针是“指向常量的指针(常量指针)”时,这个指针也可以被称为“常成员变量”吗?

@hbsun2113
Copy link
Author

hbsun2113 commented Jun 21, 2019

我大致明白了,您说的“常成员变量”应该是“常量指针”?
但这样的话,我们通过常对象只能更改常成员变量指向的值,而不能更新常成员变量吧?

@huihut
Copy link
Owner

huihut commented Jun 21, 2019

我说的 常成员变量 确实是 常量指针更新常成员变量 也就是 对常量指针重新赋值,让它指向其他对象(修改它),但是还是不能修改它指向的对象。

但刚刚测试了一下,仓库中的例子 a (const A a; // 常对象,只能调用常成员函数、更新常成员变量)实际上是不能更新常成员变量(常量指针)的,应该是例子中的 b(A b; // 普通对象,可以调用全部成员函数)才可以。

#include <iostream>
using namespace std;

class A 
{
public:
	int a1;
	const int a2;
	const int* a3;
	A(int _i1, int _i2) :a1(_i1), a2(_i2), a3(&a1) {}
	void fun1() { a3 = &a2; std::cout << "fun1()" << std::endl; }
	void fun2() const { std::cout << "fun2() const" << std::endl; }
};

int main()
{
	A b(1, 2);
	b.a3 = &b.a2;		// 可以更新常成员变量
	std::cout << *b.a3 << std::endl;

	const A a(3, 4);
	a.fun1();		// 编译出错,不可以调用普通成员函数
	a.fun2();		// 可以调用常成员函数
	a.a3 = &a.a2;		// 编译出错,不可更新常成员变量

	return 0;
}

huihut added a commit that referenced this issue Jun 21, 2019
This was referenced Apr 6, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants