gpt4 book ai didi

c++ - 错误 : "function" is private void, 错误:在此上下文中

转载 作者:行者123 更新时间:2023-11-27 22:46:00 29 4
gpt4 key购买 nike

我是 C++ 的新手,我想了解为什么我的程序会给我这个错误。我构建了一个程序来模拟一群兔子。能够自动添加他们,给他们名字、年龄等。

这些是我得到的错误:

main2.cpp: In function ‘int main()’:
main2.cpp:109:6: error: ‘void Bunny::printBunny()’ is private
void printBunny()
^
main2.cpp:132:26: error: within this context
colony[ i ].printBunny();
^

这是我想出的代码。

enter code here
#include <iostream>
#include <string>
#include <ctime>
#include <vector>
#include <cstdlib>

using namespace std;

void setSex( void );
char getSex();
void setColor( void );
string getColor();
void setAge( void );
int getAge();
void setName( void );
string getName();
void printBunny();

static const int POSSIBLE_NAMES = 5;
static const int POSSIBLE_COLORS = 4;

class Bunny
{
char sex;
string color;
int age;
string name;

bool radioactive_mutant_vampire_bunny;

BunnyData()
{
//srand( time( 0 ) );

setSex();
setColor();
setAge();
setName();
}

void setSex()
{
int randomNumber = 1 + rand() % 2;

( randomNumber == 1 ) ? sex = 'm' : sex = 'f';
}

char getSex()
{
return sex;
}

void setColor()
{
//color = possibleColors[ 0 + rand() % POSSIBLE_COLORS ];
}

string getColor()
{
return color;
}

void setAge()
{
age = 0;
}

int getAge()
{
return age;
}

void setName()
{
//name = possibleNames[ 0 + rand() % POSSIBLE_NAMES ];
}

string getName()
{
return name;
}

void printBunny()
{
cout << "Name: " << getName() << endl;
cout << "Sex: " << getSex() << endl;
cout << "Color: " << getColor() << endl;
cout << "Age: " << getAge() << endl;
}
};

int main()
{

vector< Bunny > colony;

cout << "Welcome to Bunny Graduation!" << endl << endl;

for( int i = 0; i < 5; ++i )
{
colony.push_back( Bunny() );
}

for( int i = 0; i < 5; ++i )
{
colony[ i ].printBunny();
cout << endl;
}

return 0;
}

最佳答案

除非另有说明,否则类中的所有内容都具有私有(private)访问权限例如,

class access
{
int iAmPrivate; // private. Not accessible outside of the class
public:
int getValue() //public and accessible to all
{
return iAmPrivate;
}
int iAmPublic; //also public
}

Documentation on access levels .

关于c++ - 错误 : "function" is private void, 错误:在此上下文中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42870748/

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