【发布时间】:2022-01-13 02:48:42
【问题描述】:
我想在伴随对象中创建一个受保护的变量。我认为当我使变量受保护时,它只能从继承变量类的另一个类访问,而不是从其他类或函数访问。但它不起作用。
这是我的代码
open class Population{
companion object{
@JvmStatic // Though I added it because of recommendation of IntelliJ, It still doesn't work.
protected var population_quantity: Int = 0
}
}
class Marin : Population(){
init{
population_quantity += 1 // I want to make it possible
}
}
class Checker : Population() {
fun printPopulationQuantity()
{
println(population_quantity) // I also want to make it possible
}
}
fun main(){
var m1 = Marin()
var checker = Checker()
// But I want to make codes below here impossible
// Population.population_quantity += 1
// println(Population.population_quantity)
}
以下是我想要通过 C++ 制作的内容。我希望下面能澄清我在说什么。
#include <iostream>
class Population
{
protected:
static int population_quantity;
};
int Population::population_quantity = 0;
class Marin : Population
{
public:
Marin()
{
std::cout << "Marin is generated" << std::endl;
population_quantity += 1;
}
~Marin()
{
std::cout << "Marin is dead" << std::endl;
population_quantity -= 1;
}
};
class Checker : Population
{
public:
void printPopulationQuantity()
{
std::cout << population_quantity << std::endl;
}
};
int main()
{
Checker checker;
checker.printPopulationQuantity();
Marin *m1 = new Marin();
checker.printPopulationQuantity();
// std::cout << "population : " << Population::population_quantity << std::endl;
// Can't access population_quantity from main which doesn't inherite Population
// because Population::population_qantity is protected.
// But it is possible to access Population:population_quantity from Marin which inherits Population.
delete m1;
checker.printPopulationQuantity();
return 0;
}
当你帮我解决这个问题时,我相信我会从心底里感激不尽。
【问题讨论】:
-
和c++有什么关系?
-
@ÖöTiib 如果您指的是标签,我只是添加它以正确突出显示 C++ 代码。如果仅出于此目的添加 C++ 标签不合适,我将删除它。
-
哦。请参阅stackoverflow.com/editing-help,了解如何以不同方式指示不同代码 sn-ps 的突出显示语言。
标签: kotlin protected companion-object