gpt4 book ai didi

c++ - 访问说明符和类和对象?

转载 作者:行者123 更新时间:2023-11-30 00:41:42 25 4
gpt4 key购买 nike

好吧,我正在尝试理解这一点,

所以一个类只是为一个对象创建一个模板。

class Bow
{

int arrows;

};

一个对象只是使用类模板创建一个特定的项目。

Bow::Bow(arrows)
{
arrows = 20;
}

还有另一个问题,公共(public)说明符用于使数据成员在对象中可用,而私有(private)说明符用于使数据成员仅在类内可用?

最佳答案

您提供的描述大部分是正确的,但您的示例并未显示您所描述的内容。

一个类描述了一组数据成员和可以在这些数据成员上调用的成员函数:

class Bow
{
public:
//Constructor
Bow::Bow()
{
arrows = 20;
}

Bow::Bow(int a)
{
arrows = a;
}


//member functions (in this case also called accessors/modifiers)
void getArrows(int a) const
{
return arrows;
}

void setArrows(int a)
{
arrows = a;
}

protected:
int arrows;
};

类的对象只是该类的一个实例。

//b and d are objects of the class Bow.
Bow b(3);//The constructor is automatically called here passing in 3
Bow d(4);//The constructor is automatically called here passing in 4
Bow e;//The constructor with no parameters is called and hence arrows = 20

注意:我有意避免使用您使用的模板一词,因为它在 C++ 中的用途与您的意思完全不同。


了解公共(public)/私有(private)/ protected 说明符:

public:表示类的对象可以直接使用成员。

protected:表示类的对象不能直接使用成员。基于该类的派生类可以使用这些成员。

private:表示类的对象不能直接使用成员。基于该类的派生类也不能使用这些成员。

所以在上面的例子中:

Bow b(3);
b.arrows = 10;//Compiling error arrows is not public so can't be accessed from an object

关于c++ - 访问说明符和类和对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3008002/

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