【2022 元宇宙基础NFT之Solidity OOP编程第10篇】3分钟了解Solidity中external、public、internal、private在状态变量和函数中的使
上一小节中,我们就有使用到public
和internal
,但是我们并没有给大家讲解更多细节,接下来我们将针对public
、external
、internal
和private
在状态变量和函数中的使用进行讲解和案例分析。
一、案例一
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract Animal {
string _birthDay; // 生日,默认权限为 internal
int public _age; // 年龄
int internal _weight; // 身高
string private _name; // 姓名
constructor() {
_age = 29;
_weight = 170;
_name = "Lucky dog";
_birthDay = "2011-01-01";
}
function birthDay() view external returns (string memory) {
return _birthDay;
}
function age() view public returns (int) {
return _age;
}
function weight() view internal returns (int) {
return _weight;
}
function name() view private returns (string memory) {
return _name;
}
function test() view internal {
// string memory newBirthDay = birthDay(); // external -》报错,birthDay() 函数只支持外部访问
int newAge = age(); // public 类型的函数
int newHeight = weight(); // internal 类型的函数
string memory newName = name(); // private 类型的函数
}
}
从上面的运行结果我们不难得出如下结论:
- 状态变量
- 状态变量不支持
external
类型 public
类型的_age
会自动生成一个_age()函数
供外部调用以便访问状态变量的值。public
类型的_age
、internal
类型的状态变量_weight
和private
类型的状态变量_name
均支持合约内部函数访问。
- 状态变量不支持
- 函数
external
类型的函数只支持外部访问,内部访问将报错。public
类型的函数birthDay()
、age()
均支持外部访问。public
、internal
、private
的类型均支持内部访问。
二、案例二,状态变量继承
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract Animal {
string _birthDay; // 生日
int public _age; // 年龄
int internal _weight; // 身高
string private _name; // 姓名
constructor() public {
_age = 29;
_weight = 170;
_name = "Lucky dog";
_birthDay = "2011-01-01";
}
function birthDay() view external returns (string memory) {
return _birthDay;
}
function age() view public returns (int) {
return _age;
}
function weight() view internal returns (int) {
return _weight;
}
function name() view private returns (string memory) {
return _name;
}
}
contract Person is Animal {
constructor() public {
_age = 50;
_weight = 270;
_birthDay = "2017-01-01";
_name = "Lucky"; // private 类型的变量
}
function test() view internal {
// string memory newBirthDay = birthDay(); // external -》报错,birthDay() 函数只支持外部访问
int newAge = age(); // public 类型的函数
int newHeight = weight(); // internal 类型的函数
string memory newName = name(); // private 类型的函数
}
}
接下来注释掉报错的代码,运行结果如下:
结论:
public
、internal
类型的状态变量均支持继承,private
类型的状态变量不支持继承。external
、public
、internal
类型的函数均支持继承,private
类型的函数不支持继承。
三、案例三,函数重写
温馨提示:此处内容已隐藏,您必须消耗1个积分后才能查看。 
或者

关注微信公众号: 程序咖元宇宙实验室
回复:程序咖巴士 ,获取验证码。
验证码:
验证码: